将此段代码用python实现
var CryptoJS = require("crypto-js");
var ciphertext = "1MpdxK203+ZrnyxuJRrYatKSBxHUIi1TSdQF2BQKXOG54plwfaB2GA==";
var key = CryptoJS.enc.Utf8.parse("11");
var parsedCiphertext = CryptoJS.enc.Base64.parse(ciphertext);
var decrypted = CryptoJS.DES.decrypt(
{
ciphertext: parsedCiphertext
},
key,
{
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}
);
var plaintext = decrypted.toString(CryptoJS.enc.Utf8);
console.log(plaintext)
def encrypt(key, text, mode):
'''
DES加密
:param key: 密钥
:param text: 待加密文本
:param mode: 模式
:return:
'''
key = key
text = text.encode('utf-8')
pad_text = pad(text, DES.block_size, style='pkcs7')
cipher = DES.new(key, mode)
enc_data = cipher.encrypt(pad_text)
return base64.b64encode(enc_data).decode('utf-8')
def decrypt(key, text, mode):
'''
DES解密
:param key: 密钥
:param text: 待解密文本
:param mode: 模式
:return:
'''
new_key = key
new_text = base64.b64decode(text) # base64解码
cipher = DES.new(new_key, mode)
dec_data = cipher.decrypt(new_text)
return dec_data[:-dec_data[-1]].decode('utf-8') # 去除末尾填充的字符
if __name__ == "__main__":
# 1MpdxK203+ZrnyxuJRrYatKSBxHUIi1TSdQF2BQKXOG54plwfaB2GA==
key = b'11'
key = key.ljust(8, b"\x00")
print(key)
pwd = '0587c1d12f7904ceed8613d8038b211c'
enc_pwd = encrypt(key, pwd, DES.MODE_ECB)
print(enc_pwd)
dec_data = decrypt(key, enc_pwd, DES.MODE_ECB)
print(dec_data)
注意: CryptoJS.enc.Utf8.parse(“11”); 如果不满8字节 DES.new(new_key, mode) 会报出异常,踩了很大的坑。
key = b’11’
key = key.ljust(8, b"\x00") 使用空字节补全