Ant*_*nAL 3 ruby encryption encoding openssl ruby-on-rails
我的RoR服务器接收一个字符串,该字符串使用带有base64编码的des3在C++应用程序中加密
密码对象创建如下:
cipher = OpenSSL::Cipher::Cipher::new("des3")
cipher.key = key_str
cipher.iv = iv_str
Run Code Online (Sandbox Code Playgroud)
key_str和iv_str:是加密算法的密钥和初始化向量的字符串表示.它们与RoR和C++应用程序相同.
RoR方面的代码如下:
result = ""
result << cipher.update( Base64.decode64(message) )
result << cipher.final
Run Code Online (Sandbox Code Playgroud)
执行最后一行代码后,我得到一个例外
OpenSSL::CipherError (bad decrypt)
Run Code Online (Sandbox Code Playgroud)
这有什么不对?有任何想法吗 ?
Eme*_*gul 14
OpenSSL :: Cipher的文档说明:
确保在使用以下任何方法之前
.encrypt或.decrypt之前致电:
- [
key=,iv=,random_key,random_iv,pkcs5_keyivgen]
在您的具体情况下,如您所见,省略调用会cipher.decrypt导致bad decrypt错误.
以下示例更正了该问题并显示了预期的行为:
require 'openssl'
require 'Base64'
# For testing purposes only!
message = 'MyTestString'
key = 'PasswordPasswordPassword'
iv = '12345678'
# Encrypt plaintext using Triple DES
cipher = OpenSSL::Cipher::Cipher.new("des3")
cipher.encrypt # Call this before setting key or iv
cipher.key = key
cipher.iv = iv
ciphertext = cipher.update(message)
ciphertext << cipher.final
puts "Encrypted \"#{message}\" with \"#{key}\" to:\n\"#{ciphertext}\"\n"
# Base64-encode the ciphertext
encodedCipherText = Base64.encode64(ciphertext)
# Base64-decode the ciphertext and decrypt it
cipher.decrypt
plaintext = cipher.update(Base64.decode64(encodedCipherText))
plaintext << cipher.final
# Print decrypted plaintext; should match original message
puts "Decrypted \"#{ciphertext}\" with \"#{key}\" to:\n\"#{plaintext}\"\n\n"
Run Code Online (Sandbox Code Playgroud)