Python到C#AES CBC PKCS7

时间:2011-07-19 12:22:39

标签: c# python encryption cryptography aes

我正在尝试将此C#代码转换为Python(2.5,GAE)。问题是每次加密(在同一个字符串上)时,python脚本中的加密字符串都不同。

string Encrypt(string textToEncrypt, string passphrase)
 {
    RijndaelManaged rijndaelCipher = new RijndaelManaged();
    rijndaelCipher.Mode = CipherMode.CBC;
    rijndaelCipher.Padding = PaddingMode.PKCS7;

    rijndaelCipher.KeySize = 128;
    rijndaelCipher.BlockSize = 128;
    byte[] pwdBytes = Encoding.UTF8.GetBytes(passphrase);
    byte[] keyBytes = new byte[16];
    int len = pwdBytes.Length;
    if (len > keyBytes.Length)
    {
        len = keyBytes.Length;
    }
    Array.Copy(pwdBytes, keyBytes, len);
    rijndaelCipher.Key = keyBytes;
    rijndaelCipher.IV = new byte[16];
    ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
    byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
    return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length));
}

Python代码:(PKCS7Encoder:http://japrogbits.blogspot.com/2011/02/using-encrypted-data-between-python-and.html

from Crypto.Cipher import AES
from pkcs7 import PKCS7Encoder
#declared outside of all functions
key = '####'
mode = AES.MODE_CBC
iv = '\x00' * 16
encryptor = AES.new(key, mode, iv)
encoder = PKCS7Encoder()

def function(self):
 text = self.request.get('passwordTextBox')
 pad_text = encoder.encode(text)
 cipher = encryptor.encrypt(pad_text)
 enc_cipher = base64.b64encode(cipher)

C#代码是继承的。 Python代码必须以相同的方式加密和解密,以便C#代码可以正确解码值。

注意:我是python的菜鸟:)

编辑:抱歉。应该区分出有一个函数被调用。

谢谢!

4 个答案:

答案 0 :(得分:3)

将python代码更改为:

from Crypto.Cipher import AES
from pkcs7 import PKCS7Encoder
#declared outside of all functions
key = '####'
mode = AES.MODE_CBC
iv = '\x00' * 16
encoder = PKCS7Encoder()

def function(self):
 encryptor = AES.new(key, mode, iv)**
 text = self.request.get('passwordTextBox')
 pad_text = encoder.encode(text)
 cipher = encryptor.encrypt(pad_text)
 enc_cipher = base64.b64encode(cipher)

如果有人通过谷歌访问此页面

答案 1 :(得分:3)

您的C#代码无效。

Encrypt函数将密码短语视为string passphrase,但后来尝试在此行byte[] pwdBytes = Encoding.UTF8.GetBytes(key);中引用密码

key更改为passphrase

这两个函数现在为我产生相同的结果:

<强>的Python

secret_text = 'The rooster crows at midnight!'
key = 'A16ByteKey......'
mode = AES.MODE_CBC
iv = '\x00' * 16

encoder = PKCS7Encoder()
padded_text = encoder.encode(secret_text)

e = AES.new(key, mode, iv)
cipher_text = e.encrypt(padded_text)

print(base64.b64encode(cipher_text))

# e = AES.new(key, mode, iv)
# cipher_text = e.encrypt(padded_text)
# print(base64.b64encode(cipher_text))

C#(上面提到的拼写错误修复)

Console.WriteLine(Encrypt("The rooster crows at midnight!", "A16ByteKey......"));

Python结果

  

XAW5KXVbItrc3WF0xW175UJoiAfonuf + s54w2iEs + 7A =

C#结果

  

XAW5KXVbItrc3WF0xW175UJoiAfonuf + s54w2iEs + 7A =

我怀疑你多次在你的python代码中重复使用'e'。如果你取消注释我的python脚本的最后两行,你会看到输出现在是不同的。但如果你取消注释最后三行,你会看到输出是相同的。正如Foon所说,这是由于how CBC works

CBC(密码块链接)在加密块中的字节序列时起作用。第一个块通过将IV与明文的第一个字节(“公鸡......”)合并来加密。第二个块使用第一个操作的结果而不是IV。

当您再次呼叫e.encrypt()时(例如,通过取消对python脚本的最后两行的解除),您将从中断的位置开始。它将使用最后一个加密块的输出,而不是在加密第一个块时使用IV。这就是结果看起来不同的原因。通过解开python脚本的最后三行,您初始化一个新的加密器,它将使用IV作为其第一个块,从而使您获得相同的结果。

答案 2 :(得分:1)

这种esotic PKCS7编码器是一个功能,可以填充静态长度。 所以我用一个代码片段实现了它

#!/usr/bin/env python

from Crypto.Cipher import AES
import base64

# the block size for the cipher object; must be 16, 24, or 32 for AES
BLOCK_SIZE = 16

# the character used for padding--with a block cipher such as AES, the value
# you encrypt must be a multiple of BLOCK_SIZE in length.  This character is
# used to ensure that your value is always a multiple of BLOCK_SIZE

# PKCS7 method
PADDING = '\x06'
mode = AES.MODE_CBC
iv = '\x08' * 16 # static vector: dangerous for security. This could be changed periodically
# 

# one-liner to sufficiently pad the text to be encrypted
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

# one-liners to encrypt/encode and decrypt/decode a string
# encrypt with AES, encode with base64
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)



def CryptIt(password, secret):
    cipher = AES.new(secret, mode, iv)
    encoded = EncodeAES(cipher, password)
    return encoded

def DeCryptIt(encoded, secret):
    cipher = AES.new(secret, mode, iv)
    decoded = DecodeAES(cipher, encoded)
    return decoded

我希望这可以提供帮助。 干杯

答案 3 :(得分:0)

微软对PKCS7的实现与Python有点不同。

这篇文章帮助我解决了这个问题: http://japrogbits.blogspot.com/2011/02/using-encrypted-data-between-python-and.html

他的pkcs7编码和解码代码在github上: https://github.com/janglin/crypto-pkcs7-example

使用该PKCS7库,此代码对我有用:

from Crypto.Cipher import AES

aes = AES.new(shared_key, AES.MODE_CBC, IV)
aes.encrypt(PKCS7Encoder().encode(data))