开发者

OpenSSL Command Line and Ruby OpenSSL library differ when using same parameters to encrypt text

开发者 https://www.devze.com 2023-04-06 10:17 出处:网络
Note:Using OpenSSL for symmetric encryption of text. I made a Ruby script to test OpenSSL and I found I\'m getting different results.The key, iv, and ciphers are identical, so I would expect the resu

Note: Using OpenSSL for symmetric encryption of text.

I made a Ruby script to test OpenSSL and I found I'm getting different results. The key, iv, and ciphers are identical, so I would expect the results to be identical. But they are not. Here's my script:

require 'openssl'
require 'base64'

key = "00000000000000000000000000000000"
iv = "00000000000000000000000000000000"

### OPENSSL Command Line ###
puts "*** OpenSSL Command Line ***"
print "Encrypted via Command Line:  "
string = `printf %s \"Hello\" | openssl enc -aes-128-cbc -K #{key} -iv #{iv} -base64`

puts string
puts string.inspect

print "Decrypted Data is:  "
puts `printf %s \"BC2+AQJ6ZQx0al3GXba+EQ==\n\" | openssl enc -d -aes-128-cbc -K #{key} -  iv #{iv} -base64`
puts "\n"

### Ruby OpenSSL Library ###
puts "*** OpenSSL Ruby Library ***"

cipher = OpenSSL::Cipher.new('aes-128-cbc').encrypt
cipher.padding = 1
cipher.key = key
cipher.iv = iv

encrypted_data = cipher.update("Hello")
encrypted_data << cipher.final
encrypted_data = Base64.encode64(encrypted_data)
puts "Encrypted via Ruby is: #{encrypted_data}"
puts encrypted_data.inspect

decipher = OpenSSL::Cipher.new('aes-128-cbc').decrypt
decipher.key = key
decipher.iv = iv

data = decipher.update(Base64.decode64(encrypted_data))
data << decipher.final
puts "Decrypted Data:  #{data}"

The results are:

*** OpenSSL Command Line ***
Encrypted via Command Line:  BC2+AQJ6ZQx0al3GXba+EQ==
"BC2+AQJ6ZQx0al3GXba+EQ==\n"
Decrypted Data is:  Hello

*** OpenSSL Ruby Library ***
Encrypted via Ruby is: ZkeNEgs开发者_开发技巧UXi1J7ps6kCQxdQ==
"ZkeNEgsUXi1J7ps6kCQxdQ==\n"
Decrypted Data:  Hello

Just a curious result. Any idea what's causing the data to be different?


Just a guess, without knowing Ruby's OpenSSL interface:

You give the keys and initialization vector to the command line OpenSSL in hexadecimal encoding. E.g. your key and initialization vector are 0x000....

I suppose your Ruby library takes the key and initialization vector as binary data, e.g you are actually passing a key and initialization vector consisting of 0x30303030... (assuming ASCII or anything compatible to it) instead of 0x00000....


Pack them to a binary(Hex) sequence will fix it. Test on my machine(Mac ox 10.11.1 ruby-2.2.3).

cipher.key = ["#{key}"].pack('H*')
cipher.iv = ["#{iv}"].pack('H*')

ruby Packs

decipher.key = ["#{key}"].pack('H*')
decipher.iv = ["#{iv}"].pack('H*')
0

精彩评论

暂无评论...
验证码 换一张
取 消