【发布时间】:2020-01-09 07:32:14
【问题描述】:
您好,我在 python2 中使用 pycrypto 编写了一个代码来加密和解密字符串,这里是代码
hex_key_bytes = array.array('B', [0xb8, 0xf4, 0xc9, 0x57, 0x6e, 0x12, 0xdd, 0x0d,0xb6, 0x3e, 0x8f, 0x8f, 0xac, 0x2b, 0x9a, 0x39]); # Python 2
hex_iv_bytes = array.array('B', [0xc7, 0x0f, 0x09, 0x5d, 0x8b, 0xb1, 0xa0, 0x60, 0x69, 0x9f, 0x7c, 0x19, 0x97, 0x4a, 0x1a, 0xa0]) # Python 2
BLOCK_SIZE = 16
# Decryption Functions - START
def decrypt_message(message):
encrypted_msg = message;
cipher = AES.new(hex_key_bytes, AES.MODE_CBC, hex_iv_bytes);
test = cipher.decrypt(encrypted_msg.decode('hex')) #.rstrip('\x00')
filtered_string =filter(lambda x: x in string.printable, test)
return filtered_string
# Decryption Functions - END
#Encryption Functions - START
#pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
# chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
chr(0)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
def encrypt_msg(message):
raw = pad(message)
while(len(raw) != 48):
raw = raw+chr(0)
cipher = AES.new(hex_key_bytes, AES.MODE_CBC, hex_iv_bytes)
encrypted_msg = (cipher.encrypt(raw)).encode("hex")
#logger.info("Writing encrypted packet to device " +encrypted_msg)
return encrypted_msg
我正在尝试在 python3 中迁移解决方案
这是我所做的更改
from Crypto.Cipher import AES
import string
BLOCK_SIZE = 16
hex_key_bytes = 'b8f4c9576e12dd0db63e8f8fac2b9a39'
hex_iv_bytes = 'c70f095d8bb1a060699f7c19974a1aa0'
hex_key_bytes = bytes.fromhex(hex_key_bytes)
hex_iv_bytes = bytes.fromhex(hex_iv_bytes)
# Decryption Functions - START
def decrypt_message(message):
encrypted_msg = message;
cipher = AES.new(hex_key_bytes, AES.MODE_CBC, hex_iv_bytes);
test = cipher.decrypt(encrypted_msg.fromhex()) #.rstrip('\x00')
filtered_string =filter(lambda x: x in string.printable, test)
return filtered_string
# Decryption Functions - END
#Encryption Functions - START
#pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
# chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
chr(0)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
def encrypt_msg(message):
raw = pad(message)
while(len(raw) != 48):
raw = raw+chr(0)
cipher = AES.new(hex_key_bytes, AES.MODE_CBC, hex_iv_bytes)
print(cipher.encrypt(raw))
encrypted_msg = (cipher.encrypt(raw)).hex()
#logger.info("Writing encrypted packet to device " +encrypted_msg)
return encrypted_msg
但我面临的问题是加密字符串对于两者都不相同
中的相同文本python3 --> 39c457ed7a0b6c61b936d538f9cd7815b48e674ead3cb810f20f57899c4a1b980d3206e421f045758a5ef07efd35e55f
python3 -> 6055565cab3ae7229c8148d32d4f3397477b9cdf6b91252900c95d7509e52e80f6f42227d9b111176f6b662113900fb7
我该如何解决?
【问题讨论】:
-
cipher-对象是有状态的。因此删除第二个 sn-p 中的行print(cipher.encrypt(raw))并再次比较结果。或者,可以在print-call 之后创建一个新的cipher-object。 -
是的,我已经做到了,并解决了目的。但仍然停留在解密功能上,因为 python 3 不支持 .decode('hex') 并且我尝试过 .hex() ,但没有得到正确的结果。我所取得的成就,两个加密功能都产生了相同的结果。
-
谢谢解决问题
标签: python python-3.x python-2.7 pycrypto pycryptodome