2016-10-16 194 views
1

generating一个32字节的密钥和16字节的IV为我的AES-256 CBC Ruby encryption implementation将二进制字符串(SecureRandom.random_bytes)转换为十六进制字符串?

key   = SecureRandom.random_bytes(32)  # => "m\xD4\x90\x85\xF9\xCD\x13\x98\xAB\v\xBB\xCD\x0E\x17\xFAA\xF9\x99\xAF\e\x8A\xB5\x8Ate\x93[m\x9As\xC7\xCB" 
iv   = SecureRandom.random_bytes(16)  # => "\xDF\x95[\xD5\xDD(\x0F\xB8SE\xFCZr\xF1\xB1W" 
ruby_cipher = SymmetricEncryption::Cipher.new(
    key: key, 
    iv: iv, 
    cipher_name: 'aes-256-cbc' 
) 
ruby_cipher.encrypt("Hello!")     # => 'qAnTLy7jyiLRkUqBnME8sw==' 

问:

如何转换的关键和IV为十六进制字符串,所以我可以将它们传输到其他应用程序?

语境:

在另一个应用程序中,使用JavaScript via CryptoJS我需要接受密钥和IV,并将其转换回字节是这样的:

CryptoJS.AES.encrypt(
    "Hello!", 
    CryptoJS.enc.Utf8.parse(key), 
    { iv: CryptoJS.enc.Utf8.parse(iv) } 
).toString()          // 'qAnTLy7jyiLRkUqBnME8sw==' 

在第三PHP应用程序,我将使用十六进制字符串直接,就像这样:

<?php 
openssl_encrypt(
    'Hello!', 'aes-256-cbc', 
    key, 
    0, 
    iv 
);            // => 'qAnTLy7jyiLRkUqBnME8sw==' 

回答

1

我想这应该做的工作:

key = SecureRandom.random_bytes(32) 
key_as_str = key.each_byte.map{ |byte| '%02x' % byte }.join 

我做了验证与以下脚本此解决方案:

test.rb

require 'securerandom' 
require 'symmetric-encryption' 

key   = SecureRandom.random_bytes(32) 
iv   = SecureRandom.random_bytes(16) 
ruby_cipher = SymmetricEncryption::Cipher.new(
    key: key, 
    iv: iv, 
    cipher_name: 'aes-256-cbc' 
) 
hex_key = key.each_byte.map{ |byte| '%02x' % byte }.join 
hex_iv = iv.each_byte.map{ |byte| '%02x' % byte }.join 
encoded = ruby_cipher.encrypt("Hello!") 

puts "Ruby encoded: #{encoded}" 

system("php test.php #{hex_key} #{hex_iv}") 

test.php

<?php 
$encoded = openssl_encrypt(
    'Hello!', 'aes-256-cbc', 
    hex2bin($argv[1]), 
    0, 
    hex2bin($argv[2]) 
); 

print "php encoded: $encoded\n"; 

看起来我的机器上是相同的。

+0

您确定这会生成正确的十六进制字符串吗?当试图将Hex转换后的字符串插入到我的Javascript实现中时,我得到了不同的加密结果。我还想在Ruby中加密一个字符串,然后尝试用Javascript解密它,但没有成功。 – ChristofferJoergensen

+0

你是对的。我的第一个代码没有为小数字添加0。例如,10简单地转换为'a'而不是'0a'。我确实增强了我的例子。 – slowjack2k

+0

嗯奇怪,我仍然得到不同的结果,我的Ruby和JS实现。但是你确定转换本身是正确的吗?那么也许我的问题在别的地方。 – ChristofferJoergensen

相关问题