Search code examples
rubyencryptionopensslaescbc-mode

Ruby OPENSSL AES128 CBC decrypting with random iv not working


I'm using a fairly simple encryption/decryption Ruby script, and it seems to work - BUT the decryption bit corrupts the first few bytes of the message. What am I missing?

Here's the code:

key = OpenSSL::Random.random_bytes(16)
plain_text = "Some important txt we want to encrypt"
cipher = OpenSSL::Cipher::AES128.new(:CBC)
cipher.encrypt
cipher.key = key
cipher.random_iv
cipher_text = cipher.update(plain_text) + cipher.final

cipher = OpenSSL::Cipher::AES128.new(:CBC)
cipher.decrypt
cipher.key = key
cipher.random_iv
decrypted_plain_text = cipher.update(cipher_text) + cipher.final

puts "AES128 in CBC mode"
puts "Plain text: " + plain_text
puts "Cipher text: " + urlsafe_encode64(cipher_text)
puts "Decrypted plain text: " + decrypted_plain_text

And the outcome:

AES128 in CBC mode Plain text: Some important txt we want to encrypt
Cipher text:
P2fdC7cApQvxHnfxSEfB2iJaueK3xRoj-NN3bDR8JheL_VPFYTDF_RxpLfBwoRfp
Decrypted plain text: �܇�Σ }w�D�A:xt we want to encrypt

Solution

  • You're using a different, random IV on the decryption. This value must be identical. That is you capture it when encrypting:

    iv = cipher.random_iv
    

    Then you decrypt using that:

    cipher.iv = iv
    

    Then it decrypts properly. You need the same key + IV pair in order for the decryption to succeed.