2016-10-16 190 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

相關問題