Python AES encryption and Ruby encryption - other behavior?

From this site I have this piece of code:

>>> from Crypto.Cipher import AES >>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456') >>> message = "The answer is no" >>> ciphertext = obj.encrypt(message) >>> list(bytearray(ciphertext)) [214, 131, 141, 100, 33, 86, 84, 146, 170, 96, 65, 5, 224, 155, 139, 241] 

When I take this array and turn it into a string in Ruby and continue to decrypt it, an error occurs:

 >> require 'openssl' => true >> obj2 = OpenSSL::Cipher::Cipher.new("AES-128-CBC") => #<OpenSSL::Cipher::Cipher:0x007fa388389b30> >> obj2.decrypt => #<OpenSSL::Cipher::Cipher:0x007fa388389b30> >> obj2.key = 'This is a key123' => "This is a key123" >> obj2.iv = 'This is an IV456' => "This is an IV456" >> ciphertext = [214, 131, 141, 100, 33, 86, 84, 146, 170, 96, 65, 5, 224, 155, 139, 241].pack('c*') => "\xD6\x83\x8Dd!VT\x92\xAA`A\x05\xE0\x9B\x8B\xF1" >> obj2.update(ciphertext) + obj2.final OpenSSL::Cipher::CipherError: bad decrypt from (irb):20:in `final' from (irb):20 from /home/danyel/.rbenv/versions/2.0.0-p0/bin/irb:12:in `<main>' 

Why is this not working?

+8
python ruby encryption aes
source share
1 answer

This is understandably confusing - PyCrypto got a little off track and broke down with the usual implementation. If you are familiar enough with what encrypted data usually looks like, Python's output looks clearly erroneous and gives you the opportunity to get started. If you do not, then it’s easy to ask what the hell went wrong, and I don’t know where to start.

In the "normal" implementation, the add-on will be used by default, and you will end (in this case) with an encrypted output that will contain 16 bytes.

Encrypted using Ruby, for example, this is the result:

 >> ciphertext => "\xD6\x83\x8Dd!VT\x92\xAA`A\x05\xE0\x9B\x8B\xF1\xD5f\xC7\xFFNI\xC7N\xBC-;!\f\xF1!\xB4" >> ciphertext.bytes => [214, 131, 141, 100, 33, 86, 84, 146, 170, 96, 65, 5, 224, 155, 139, 241, 213, 102, 199, 255, 78, 73, 199, 78, 188, 45, 59, 33, 12, 241, 33, 180] 

PyCrypto, for reasons that I cannot immediately find, chose to work only with loose data . When exchanging data with PyCrypto, you want to configure any other libraries accordingly.

In the case of the Ruby OpenSSL library, the Cipher object provides a padding property that can be used to disable padding:

 >> require 'openssl' => true >> obj2 = OpenSSL::Cipher::Cipher.new("AES-128-CBC") => #<OpenSSL::Cipher::Cipher:0x007fe62407a9b0> >> obj2.decrypt => #<OpenSSL::Cipher::Cipher:0x007fe62407a9b0> >> obj2.key = 'This is a key123' => "This is a key123" >> obj2.iv = 'This is an IV456' => "This is an IV456" >> obj2.padding = 0 => 0 >> ciphertext = [214, 131, 141, 100, 33, 86, 84, 146, 170, 96, 65, 5, 224, 155, 139, 241].pack('c*') => "\xD6\x83\x8Dd!VT\x92\xAA`A\x05\xE0\x9B\x8B\xF1" >> obj2.update(ciphertext) + obj2.final => "The answer is no" 
+10
source share

All Articles