3

我正在尝试使用密码在 Ruby 中使用 OpenSSL 库加密数据。Ruby 代码如下所示:

require('openssl')
require('base64')

cipher = OpenSSL::Cipher.new ('AES-256-CBC')
cipher.encrypt
cipher.iv = iv = cipher.random_iv

pwd = 'topsecret'
salt = OpenSSL::Random.random_bytes 8
iter = 10000
key_len = cipher.key_len
digest = OpenSSL::Digest::SHA256.new

key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)
cipher.key = key

puts "salt=#{salt.unpack('H*')[0]}"
puts "key=#{key.unpack('H*')[0]}"
puts "iv=#{iv.unpack('H*')[0]}"

encrypted = cipher.update 'my data to encrypt'
encrypted << cipher.final

puts "encrypted=#{Base64.strict_encode64(encrypted)}"

# it returns:
# salt=1332e5603cbc018a
# key=11a168cf01556a5ee3e22e049f0e65d3adcd75f39e32c7d19aec32a0ccb40d93
# iv=35a08f2d3e719abbee78a0f4fe47c938
# encrypted=E3Ag6cRL2R+xytgw01i6tKSFpV7s7bKoiiWvPA1FYxM=

不幸的是,当我尝试对此进行解密时,出现错误bad magic number

$ echo "E3Ag6cRL2R+xytgw01i6tKSFpV7s7bKoiiWvPA1FYxM=" | openssl enc -aes-256-cbc -base64 -d -p -pass pass:topsecret
bad magic number

openssl enc但是,当我通过运行命令在终端中尝试此操作时,它可以工作:

$ echo 'my data' | openssl enc -aes-256-cbc -base64 -p -pass pass:topsecret                            
salt=8135837A305553F2
key=8B4373ABD786BAC107F4112640E95E920C77C017FCEC18E1BD919CED42F0298E
iv =910637CE50FADF27D944B7A8DD239E6D
U2FsdGVkX1+BNYN6MFVT8oWa5P/oxZFwzMk1DRCSSGg=

$ echo "U2FsdGVkX1+BNYN6MFVT8oWa5P/oxZFwzMk1DRCSSGg=" | openssl enc - aes-256-cbc -d -p -base64 -pass pass:topsecret
salt=8135837A305553F2
key=8B4373ABD786BAC107F4112640E95E920C77C017FCEC18E1BD919CED42F0298E
iv =910637CE50FADF27D944B7A8DD239E6D
my data

我想我尝试了从密码生成密钥/IV 的所有可能组合,但每次都会出错。有没有人能够发现这种方式的问题在哪里?我花了一整天的时间在这上面。

4

0 回答 0