Python在CBC加密模式下实现AES
我正在尝试完成在线挑战,它要求我们自己实现AES CBC模式,而不使用任何库函数来完成这项工作(ofc xD)。我正在为AES模块使用Python在CBC加密模式下实现AES,python,encryption,aes,pycrypto,cbc-mode,Python,Encryption,Aes,Pycrypto,Cbc Mode,我正在尝试完成在线挑战,它要求我们自己实现AES CBC模式,而不使用任何库函数来完成这项工作(ofc xD)。我正在为AES模块使用python3.7和PyCrypto(顺便说一句,我是python初学者) 我觉得自己找到了解决办法,但事实并非如此,我不知道自己做错了什么。 我正在输入以下文本:` 2017年9月2017年9月2017年9月 2017年 ` 使用此键: 黄色潜艇 并且有一个16字节长的IV,完全是0(\x00) 但是我的输出与我可以在网上找到的不同网站不同,或者使用PyCryp
python3.7
和PyCrypto
(顺便说一句,我是python初学者)
我觉得自己找到了解决办法,但事实并非如此,我不知道自己做错了什么。
我正在输入以下文本:`
2017年9月2017年9月2017年9月
2017年
`
使用此键:
黄色潜艇
并且有一个16字节长的IV,完全是0(\x00)
但是我的输出与我可以在网上找到的不同网站不同,或者使用PyCrypto
模块中的AES CBC模式时也不同
以下是我到目前为止为生成带有注释的aes cbc加密而编写的小程序:
#!/usr/bin/env python
from sys import argv
from Crypto.Cipher import AES
import codecs
def pad(plaintext):
padding_len = 16 - (len(plaintext) % 16)
print(padding_len)
if padding_len == 16:
return plaintext
padding = bytes([padding_len] * padding_len)
return plaintext + padding
def xor_for_char(input_bytes, key_input):
index = 0
output_bytes = b''
for byte in input_bytes:
if index >= len(key_input):
index = 0
output_bytes += bytes([byte ^ key_input[index]])
index += 1
return output_bytes
class AESCBCTool:
def __init__(self):
self.best_occurence = 0
self.best_line = 0
def encrypt_CBC(self, enc, key):
enc = pad(enc) # here I pad the text (PCKS#7 way)
nb_blocks = (int)(len(enc) / 16) #calculate the number of blocks I've to iter through
IV = bytearray(16)
cipher = AES.new(key, AES.MODE_ECB)
for i in range(nb_blocks):
enc2 = xor_for_char(enc[i * 16:(i + 1) * 16], IV) #xor a block with IV
IV = cipher.encrypt(enc2) # set the the IV based on the encryption of the xored text
print(codecs.decode(codecs.encode(IV, 'base64')).replace("\n", ""), end='') #print the encrypted text in base 64
def main(filepath):
f = open(filepath, "r")
if f.mode == 'r':
content = f.readlines()
tool = AESCBCTool()
for line_content in content:
tool.encrypt_CBC(bytes(line_content, "utf-8"), bytes("YELLOW SUBMARINE", "utf-8"))
f.close()
if __name__== "__main__":
try:
main(argv[1]) #this is the path to the file that contains the text
except Exception as e:
print(e)
exit(84)
exit(0)
以下是我的输出:
0TKm+DjGff6fB/l0Z+M5TQ==8DO1FSVJBN2+MhAULmjHA==w5vZtuiL2SrtSLi2CkMBzQ==nvKLm7C7QDmSxk2PqV3NHQ==2+DSu4BqXskn8/znFCUCcQ==
同时,输出应为:
IS4P7KPY9G0A68AUZPKZAZBTP0H3NYZVHPTUXNAJBS3KIUHGI3FU79E4FW+E34MIYYN5DMBLE8TQN2DVHSROM7AUPMY0ZBTLQPWU5UHOYY=
您有什么建议吗?您的pkcs7填充不正确,您的base64编码需要在整个输出上进行,而不是在每个块上。谢谢,我在base64中编码了整个输出后,它就工作了。