C#AES CBC PKCS7到Python
我目前正在尝试将一个简单的AES代码从C#翻译成Python。这两种语言我都很熟悉,但我对加密领域(尤其是AES)一无所知。我以前在C#中写过这段AES代码,但现在我不知道如何在Python中工作(我使用PyCrypto,因为Python2.7没有内置的AES)。下面是我的C#代码:C#AES CBC PKCS7到Python,c#,python,encryption,aes,pycrypto,C#,Python,Encryption,Aes,Pycrypto,我目前正在尝试将一个简单的AES代码从C#翻译成Python。这两种语言我都很熟悉,但我对加密领域(尤其是AES)一无所知。我以前在C#中写过这段AES代码,但现在我不知道如何在Python中工作(我使用PyCrypto,因为Python2.7没有内置的AES)。下面是我的C#代码: 请注意,对于Python,我还需要BlockSize=128、KeySize=256、Padding=PKCS7和Cipher CBC。提前感谢 我意识到这个问题已经存在将近一年了,但我是在寻找一些解决方案来与旧式
请注意,对于Python,我还需要BlockSize=128、KeySize=256、Padding=PKCS7和Cipher CBC。提前感谢 我意识到这个问题已经存在将近一年了,但我是在寻找一些解决方案来与旧式windows进程通信时发现的,该进程在AES的实现中使用PKCS7填充。这里有一个对我来说非常有用的例子。希望它能对其他人有用。我拥有与问题作者指定的相同的块大小、键大小和填充
from Crypto.Cipher import AES
from pkcs7 import PKCS7Encoder
import base64
shared_key = "abc123ty9TW1abc123ty9TW1" #some random key for a working example
IV = "rTF25nTrrTF25nTr"
clear_text = "Testing 123"
aes = AES.new(shared_key, AES.MODE_CBC, IV)
aes.block_size = 128
cipher_text = base64.b64encode(aes.encrypt(PKCS7Encoder().encode(clear_text)))
print(cipher_text)
aes_decrypter = AES.new(shared_key, AES.MODE_CBC, IV)
aes_decrypter.block_size = 128
clear_text = PKCS7Encoder().decode(aes_decrypter.decrypt(base64.b64decode(cipher_text)))
print(clear_text)
我使用的pkcs7填充实用程序是从以下文件复制的:
您只发布了C版本。你的Python代码的哪一部分不起作用?@Carsten嗨,我忘了澄清一下,我想得到关于将C#翻译成Python代码的帮助。我试着查看PyCrypto文档,但没有提到使用PKCS7填充/取消添加。另外,我对AES加密的内容一无所知。可能是
from Crypto.Cipher import AES
from pkcs7 import PKCS7Encoder
import base64
shared_key = "abc123ty9TW1abc123ty9TW1" #some random key for a working example
IV = "rTF25nTrrTF25nTr"
clear_text = "Testing 123"
aes = AES.new(shared_key, AES.MODE_CBC, IV)
aes.block_size = 128
cipher_text = base64.b64encode(aes.encrypt(PKCS7Encoder().encode(clear_text)))
print(cipher_text)
aes_decrypter = AES.new(shared_key, AES.MODE_CBC, IV)
aes_decrypter.block_size = 128
clear_text = PKCS7Encoder().decode(aes_decrypter.decrypt(base64.b64decode(cipher_text)))
print(clear_text)
import binascii
import StringIO
class PKCS7Encoder(object):
def __init__(self, k=16):
self.k = k
## @param text The padded text for which the padding is to be removed.
# @exception ValueError Raised when the input padding is missing or corrupt.
def decode(self, text):
'''
Remove the PKCS#7 padding from a text string
'''
nl = len(text)
val = int(binascii.hexlify(text[-1]), 16)
if val > self.k:
raise ValueError('Input is not padded or padding is corrupt')
l = nl - val
return text[:l]
## @param text The text to encode.
def encode(self, text):
'''
Pad an input string according to PKCS#7
'''
l = len(text)
output = StringIO.StringIO()
val = self.k - (l % self.k)
for _ in xrange(val):
output.write('%02x' % val)
return text + binascii.unhexlify(output.getvalue())