Jonathan Coletti
Jonathan Coletti

Reputation: 528

Implementing PKCS7 padding in python for a C# script

I have this encrypt with AES function in python:

    def encrypt_text(self):
        raw       = self.PKCS7_padding()
        iv        = Random.new().read(self.block_size)
        cipher    = AES.new(self.key, AES.MODE_CBC, iv)
        encrypted = base64.b64encode(iv + cipher.encrypt(raw))
        return encrypted

And then padding it with:

def PKCS7_padding(self):
    return self.text+chr(16-len(self.text)%16)*(16-len(self.text)%16)

But when I send it to this c# function

        public static string DecryptString(string key, string cipherText)  
        {  
            byte[] iv = new byte[16];  
            byte[] buffer = Convert.FromBase64String(cipherText);  
  
            using (Aes aes = Aes.Create())  
            {  
                aes.Key = Convert.FromBase64String(key);  
                aes.IV = iv;  
                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);  
  
                using (MemoryStream memoryStream = new MemoryStream(buffer))  
                {  
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read))  
                    {  
                        using (StreamReader streamReader = new StreamReader((Stream)cryptoStream))  
                        {  
                            return streamReader.ReadToEnd();  
                        }  
                    }  
                }  
            }  
        }

Say i send "hello world" I get a weird mix of the string i sent plus random non pritable characters. EX: "�Ȯ�Ŗf�"��Xhello world"

The key is generated as follows:

key = base64.b64encode(os.urandom(32))
return key.decode()

I do not get any errors but weird text any ideas Thanks! If you have any questions please feel free to ask

Upvotes: 2

Views: 505

Answers (1)

Topaco
Topaco

Reputation: 49415

In the Python code, a random IV is generated and concatenated with the ciphertext. However, in the C# code, the separation of IV and ciphertext is missing. Instead, a zero IV is applied and the concatenation of IV and ciphertext is decrypted, which causes the problem.

The separation of IV and ciphertext can be added to the C# code e.g. as follows:

byte[] buffer = ...

byte[] ct = new byte[buffer.Length - iv.Length];
Buffer.BlockCopy(buffer, 0, iv, 0, iv.Length);
Buffer.BlockCopy(buffer, iv.Length, ct, 0, ct.Length);
buffer = ct;

using ...

Note that PyCryptodome supports padding in a dedicated module: Crypto.Util.Padding.

Also, in the Python code the Base64 encoded key is nowhere Base64 decoded (but maybe the corresponding code was just not posted).

Upvotes: 1

Related Questions