AES Python encryption and Ruby encryption - different behaviour?

前端 未结 1 1552
天涯浪人
天涯浪人 2021-01-17 23:58

From this site I have this code snippet:

>>> from Crypto.Cipher import AES
>>> obj = AES.new(\'This is a key123\', AES.MODE_CBC, \'This is          


        
相关标签:
1条回答
  • 2021-01-18 00:42

    This is understandably confusing—PyCrypto has gone a bit off the rails here and broken with the usual implementation. If you're familiar enough with what encrypted data should normally look like, the Python output looks blatantly wrong and gives you a place to start. If you're not, it's easy to wonder what the heck went wrong and have no idea where to start looking.

    In a "normal" implementation, padding will be used by default and you'll end up (in this case) with encrypted output that's 16 bytes longer.

    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 I cannot immediately find, has chosen to work only with unpadded data. When interchanging data with PyCrypto, you'll want to configure any other libraries appropriately.

    In the case of Ruby's OpenSSL library, the Cipher object exposes a padding property which 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"
    
    0 讨论(0)
提交回复
热议问题