Python 上的 3DES 加密产生与 Nodejs/Java 不同的结果

3DES crypto on Python produces different result from Nodejs/Java

我正在构建一个需要信用卡 3DES 加密的结帐, 但我在 Python 和 NodeJs 上得到了不同的结果。

Python代码: (我正在使用 pycryptodome 包)

import binascii
import base64
from Crypto.Cipher import DES3
import json

iv = '04njBuE3/dc='
iv = base64.b64decode(iv)
key = 'DpzDLcvVCHdVoRqE/NuIHs0QJ0xFdH2p'
key = base64.b64decode(key)
data = {'CartaoNumero': '0000000000000000',
'CartaoMesAno':'00/0000',
'CartaoSeg': '000',
'CartaoNome':'Teste Teste',
'IdentFatura':'Teste',
'Valor':'1000',
'NomeCliente':'Teste Teste',
'EmailCliente':'teste@teste.com',
'CpfCliente':'11122233344'}
data = json.dumps(data)
data = base64.b64encode(data.encode('utf-8'))
#print (data)

def card_encrypt(iv,key, data):
    desT = DES3.new(key, DES3.MODE_CBC, IV=iv)
    desT_key = desT.encrypt(data)
    desT_key = base64.b64encode(desT_key)
    return (desT_key)

Result: b'+TSfdiGmLAir8RVEze4yr72d3Sm5RBkDBwLYhpv1NKIIfVM+AnIhoSArFzV5am7qOdaFO0Ob4KSS8vXRYnBAO1xyk9MEoNc93uf/53cCMVHbZ8FUx14Vilx3Mg8+kbSMsASki5Dn+hlKE0ElFC/nyiWoOJvkWmtndoL+EEb4rkFil0zg637YXFE7f0yTOWhz97G6CEb4mvegCPpizuVdh2sBQQFDsJMEQE1kGeY2gDiDADwRQiMTrznhWFn3H6SylMxjQaNJTxu820BNitefMgcwAUTUJSrZt6DyuJ59e7772DK2jLubpK8/8xNolKalcjYMx106T7jOxDoPWZEoIe7YSGn9+Z3IGe5R7YFQJVLJUJ3SzlwWLptr3ZbMRnDCh2rB4FbTsM4igic4ZUQjS3DUzUVpT5URQyGjJK9+434ivMehknko4x+1owaEgcLGsPT9zBADlKFQ+OE8JqOhwJ5IztyoWeOmBVPZsOQdYvo='

Nodejs 代码:

var secretKey = 'DpzDLcvVCHdVoRqE/NuIHs0QJ0xFdH2p'
 var secretIV = '04njBuE3/dc='
 var dataOfCard = {'CartaoNumero': '0000000000000000',
'CartaoMesAno':'00/0000',
'CartaoSeg': '000',
'CartaoNome':'Teste Teste',
'IdentFatura':'Teste',
'Valor':'1000',
'NomeCliente':'Teste Teste',
'EmailCliente':'teste@teste.com',
'CpfCliente':'11122233344'}

const crypto = require('crypto');
 
async function encryptCardData(dataOfCard, secretKey, secretIV) {
    try {
        const des3_key = new Buffer.from(secretKey, "base64");
        console.log(des3_key)
        const des3_iv = new Buffer.from(secretIV, "base64");
        console.log(des3_iv)
        const cardString = JSON.stringify(dataOfCard);
        console.log(cardString)
      
        const cipher = crypto.createCipheriv('des-ede3-cbc', des3_key, des3_iv);

        const encrypted = cipher.update(cardString, 'utf8', 'base64');
    
        return encrypted + cipher.final('base64');        
    } catch (error) {
        console.error("Error:", error.message);
        throw error;
    }
}

encryptCardData(dataOfCard, secretKey, secretIV)

Result: '7pkXCZCKIDY1ueGwkfLk5W5AnDw2iP4jiZ5YHUBRMd56eDhVyZvnJ6EG+mh/wmHl3ljrJ+sfDMgAbpOgljRRQb4pOc1LQKHdkgcl3ZWmlvmqv8mGKdGaZYTgXnQ9pZGwoUQJAcuQgOCYWD5wMvIA6g4zd8O1iy/IsXWkBEzCkQA3x6NIkwrCNdftogu3JZlbmOIj90flo8t+J2X89rXzQmWKw6uCWrzzfGQvmvqqNf7ecDduTtCXee3WCdvcC3Ar7TbVpSv+NenoK+Oh+Tkj6Y8h4t6YAexyE8HxQ1GqCqFlMAzdCa2TtA=='

NodeJS 正在生成正确的结果。 我需要在 Python 型号上更正什么?

Python 代码与 NodeJS 代码不同,原因如下:

  • json.dumps() 到 JSON 字符串的转换与 JSON.stringify() 略有不同。 json.dumps(),与 JSON.stringify() 不同,在分隔符后插入空格(为了更好的可读性),参见 。为避免这种情况,请使用以下修改:

    dataJSON = json.dumps(data, separators=(',', ':'))
    
  • 在 NodeJS 代码中,填充是使用 PKCS7 隐式 完成的,但在 Python 中不是。此处必须 显式 执行填充,为此 PyCryptodome 提供了 padding module:

    from Crypto.Util.Padding import pad
    ...
    dataPadded = pad(dataJSON.encode('utf-8'), 8)
    

    8 是以字节为单位的 3DES 块大小。

  • 必须去掉数据的Base64编码:

    #data = base64.b64encode(data.encode('utf-8'))
    

有了那个:

ciphertext = card_encrypt(iv,key, dataPadded)
print (ciphertext)

returns密文:

b'7pkXCZCKIDY1ueGwkfLk5W5AnDw2iP4jiZ5YHUBRMd56eDhVyZvnJ6EG+mh/wmHl3ljrJ+sfDMgAbpOgljRRQb4pOc1LQKHdkgcl3ZWmlvmqv8mGKdGaZYTgXnQ9pZGwoUQJAcuQgOCYWD5wMvIA6g4zd8O1iy/IsXWkBEzCkQA3x6NIkwrCNdftogu3JZlbmOIj90flo8t+J2X89rXzQmWKw6uCWrzzfGQvmvqqNf7ecDduTtCXee3WCdvcC3Ar7TbVpSv+NenoK+Oh+Tkj6Y8h4t6YAexyE8HxQ1GqCqFlMAzdCa2TtA=='

匹配NodeJS代码的密文

请注意,3DES 已弃用,应替换为例如更现代和高性能的 AES,s。 here. Apart from that, the use of a static IV is generally insecure, s here.