我的主要目标是将该JavaScript重写为python
password = "AAAABBBBCCCC";
passwordMd5 = CryptoJS.MD5(password);
//e1b6b2b3211076a71632bbf2ad0edc05
passwordKey = CryptoJS.SHA256(CryptoJS.SHA256(passwordMd5 + data.v1) + data.v2);
//4a5148da63f40e1bcd3e3225f9b79412b7aee745f4b7f831b9d0893d0d6d666f
encryptedPassword = CryptoJS.AES.encrypt(passwordMd5, passwordKey, {mode: CryptoJS.mode.ECB,padding: CryptoJS.pad.NoPadding});
//U2FsdGVkX198V2FiYyEGAKISlXBcmad7V0scbooxQ8QMSmp84vtyAfHytynX2mrw
encryptedPassword = CryptoJS.enc.Base64.parse(encryptedPassword.toString()).toString(CryptoJS.enc.Hex);
//53616c7465645f5f7c57616263210600a21295705c99a77b574b1c6e8a3143c40c4a6a7ce2fb7201f1f2b729d7da6af0
这是我在python中的代码
passwordMd5 = hashlib.md5(password.encode("utf-8")).hexdigest()
# e1b6b2b3211076a71632bbf2ad0edc05
passwordKey = hashlib.sha256((hashlib.sha256((passwordMd5 + prelogin["v1"]).encode("utf-8")).hexdigest() + prelogin["v2"]).encode("utf-8")).hexdigest()
# 4a5148da63f40e1bcd3e3225f9b79412b7aee745f4b7f831b9d0893d0d6d666f
cipher = AESCipher(passwordKey)
encryptedPassword = cipher.encrypt(passwordMd5)
print(encryptedPassword)
AESCipher.py(原始:here),
import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
BS = 32
def pad(s): s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode()
def unpad(s): s[:-ord(s[len(s)-1:])]
class AESCipher(object):
def __init__(self, key):
self.key = key
def encrypt(self, message):
message = message.encode()
raw = pad(message)
cipher = AES.new(self.key, AES.MODE_ECB)
enc = cipher.encrypt(raw)
return base64.b64encode(enc).decode('utf-8')
def decrypt(self, enc):
enc = base64.b64decode(enc)
cipher = AES.new(self.key, AES.MODE_ECB)
dec = cipher.decrypt(enc)
return unpad(dec).decode('utf-8')
当我尝试运行它时,它给了我错误:
Traceback (most recent call last):
File "main.py", line 97, in <module>
encryptedPassword = cipher.encrypt(passwordMd5)
File "AESCipher.py", line 31, in encrypt
cipher = AES.new(self.key, AES.MODE_ECB)
File "python\lib\site-packages\Crypto\Cipher\AES.py", line 206, in new
return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
File "python\lib\site-packages\Crypto\Cipher\__init__.py", line 79, in _create_cipher
return modes[mode](factory, **kwargs)
File "python\lib\site-packages\Crypto\Cipher\_mode_ecb.py", line 177, in _create_ecb_cipher
cipher_state = factory._create_base_cipher(kwargs)
File "python\lib\site-packages\Crypto\Cipher\AES.py", line 92, in _create_base_cipher
raise ValueError("Incorrect AES key length (%d bytes)" % len(key))
ValueError: Incorrect AES key length (64 bytes)
我知道密钥的长度为64个字节,但javascript版本与相同的passwordKey
完美搭配。
我不知道我的代码有什么问题,请帮助!
答案 0 :(得分:2)
实际上AES密钥的长度应为16、24或32个字节。
您正在使用sha256哈希的十六进制摘要作为键,这将导致一个64字节的字符串。 而是执行以下操作:
password = (hashlib.sha256((passwordMd5 + prelogin["v1"])).hexdigest() + prelogin["v2"])
passwordKey = hashlib.sha256(password).digest()