Why doesn't it work when using Python for encryption and then Ruby for decryption?

I try to encrypt and then a base64_encode string using Python and base64_decode and then decrypt result with Ruby, but the string is mixed up.

I do not see the difference in the two methods. I tried using the 128-bit AES-CFB algorithm, but was not successful.

Here is my Python code:

 from Crypto.Cipher import AES from Crypto.Util.randpool import RandomPool from base64 import standard_b64encode, standard_b64decode key = "abcdefghijklmnop" en = AES.new(key, AES.MODE_CFB, "0000000000000000") cipher = en.encrypt("apple") cipher64 = standard_b64encode(cipher) 

cipher64 contains: WqF9Zj0=

My Ruby Code:

 require "openssl" require 'digest/sha2' require 'base64' de = OpenSSL::Cipher::Cipher.new("aes-128-cfb") de.decrypt de.key = "abcdefghijklmnop" de.iv = "0000000000000000" plain = de.update("WqF9Zj0=".unpack('m')[0]) de.final puts plain 

plain contains a different line than "apple" . I get the same result if the length of the string is 16 to avoid filling problems.

I assume this is a parameter problem, but I cannot figure that out. Does anyone have an idea?

+4
source share
1 answer

PyCrypto uses a different segment_size

When encoding, specify segment_size and enter plain text.

 from base64 import standard_b64encode from Crypto.Cipher import AES def pad(x, n=16): p = n - (len(x) % n) return x + chr(p) * p key = "abcdefghijklmnop" en = AES.new(key=key, mode=AES.MODE_CFB, IV="0" * 16, segment_size=128) cipher = en.encrypt(pad("apple")) cipher64 = standard_b64encode(cipher) print cipher64 

Using the code above, you will get apple\x03\x03\x03 . On the Ruby side, you have to remove the pad.

Ruby part (decoding):

 require "openssl" de = OpenSSL::Cipher::Cipher.new("aes-128-cfb") de.decrypt de.key = "abcdefghijklmnop" de.iv = "0000000000000000" plain = de.update(ARGV[0].unpack('m')[0]) + de.final plain = plain[0...-plain[-1].ord] puts plain 

Alternatively, you can use M2Crypto, which does not need to remove the strip on the Ruby side:

 from base64 import standard_b64encode import M2Crypto.EVP key = "abcdefghijklmnop" iv = "0000000000000000" en = M2Crypto.EVP.Cipher('aes_128_cfb', key, iv, 1) cipher = en.update('apple') + en.final() cipher64 = standard_b64encode(cipher) print cipher64 
+1
source

Source: https://habr.com/ru/post/1493197/


All Articles