How to resolve deprecation warnings for OpenSSL::Cipher::Cipher#encrypt

ぃ、小莉子 提交于 2019-12-03 10:00:38

Due to the implicit type conversion in Ruby, older Ruby allows people use PBE (Password-Based Encryption) in a totally wrong way. The newer one fixes that so the warning is a good thing.

Your example shows exactly the problem. Triple-DES requires 24-byte key material (including parity) but you only provided 6 bytes. Your key material will be repeated to make up the deficit, that resulted in a less secure key.

The correct way to do this is to generate key and IV (initial vector) with PKCS5, which use complicated hashing and iteration to make the key much more secure.

Ruby provides following sample code. pass is your key and you can use any hardcoded value for salt.

puts "--Encrypting--"
des = OpenSSL::Cipher::Cipher.new(alg)
des.pkcs5_keyivgen(pass, salt)
des.encrypt
cipher =  des.update(text)
cipher << des.final
puts %(encrypted text: #{cipher.inspect})
puts

puts "--Decrypting--"
des = OpenSSL::Cipher::Cipher.new(alg)
des.pkcs5_keyivgen(pass, salt)
des.decrypt
out =  des.update(cipher)
out << des.final
puts %(decrypted text: "#{out}")
puts

ZZ Coder was close, but no cigar. In fact, you should never call Cipher#pkcs5_keyivgen before #decrypt or #encrypt. In practice, generally it will encrypt fine, but decrypt will oft times fail. So the code should be:

puts "--Encrypting--"
des = OpenSSL::Cipher::Cipher.new(alg)
des.encrypt
des.pkcs5_keyivgen(pass, salt)
cipher =  des.update(text)
cipher << des.final
puts %(encrypted text: #{cipher.inspect})
puts

and

puts "--Decrypting--"
des = OpenSSL::Cipher::Cipher.new(alg)
des.decrypt
des.pkcs5_keyivgen(pass, salt)  
out =  des.update(cipher)
out << des.final
puts %(decrypted text: "#{out}")
puts
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!