Problems encoding/decoding using AES-128-CBC

故事扮演 提交于 2019-12-03 23:06:06

Ruby script is wrong. You have to first call the encrypt method, and then set the key and iv:

require 'openssl'
aes = OpenSSL::Cipher::Cipher.new("AES-128-CBC")
aes.encrypt
aes.key = "aaaaaaaaaaaaaaaa"
aes.iv = "aaaaaaaaaaaaaaaa"
encrypted = aes.update("1234567890123456") << aes.final
puts encrypted.unpack('H*').join

I figured out because when trying to decode an encrypted string I got:

aescrypt.rb:13:in `final': bad decrypt (OpenSSL::Cipher::CipherError)
    from aescrypt.rb:13:in `<main>'

Seems you found already the reason that your script does give different results.

Some more things to consider:

  • Don't ever hardcode the key in the program - that way you can't easily change it, and if someone gets access to your program code, she also gets to see the key.
  • Don't ever use a constant initialization vector. Instead, generate a random one and send it together with the ciphertext. Alternatively, if you generate the key from a password and some salt, you can also generate the IV from the same ... but don't use the key directly as IV.
  • Your key/IV values are strings, not bytes. String.getBytes() (in Java) converts the string to bytes using some encoding. The encoding used is system-dependent, and none of the usual String encodings (UTF-8, Latin-1, ...) can represent all bytes as printable (and typeable) characters. Preferably use something like Base64 or hex-encoding, if you have to store your key as string.
  • And whenever you transform a string to bytes, specify an encoding (and use the same encoding later for retrieving it).

@Cristian, For key and initial vector, you can create a function by using today's date plus the secure fixed keyword.

Eg: key = January 8, 2012 + Key

And for initial vector,

Eg: iv = January 8, 2012 + IV

Then enter that data(key and iv) to MD5 it will produce the output 16 bytes that you can use for the Key and IV. Every day, key and iv will change randomly.

Make sure both systems use the same date format and setup on the same date.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!