AES/CBC/PKCS5PADDING IV - NodeJs 中的加密(Python 加密)

时间:2021-07-14 02:58:25

标签: python node.js aes

我正在尝试在 NodeJs 中加密。它在 Python 中工作。但我无法在 Node 中实现相同的目标。

请找到我的 NodeJs 代码:

const Crypto = require('crypto');
const config = {
  host: 'http://******',
  appkey: 'app',
  secret: "****", // length is 32
  iv: "****" // length is 16
}

function enCryptoAes (data, key, iv = '') {
    let clearEncoding = 'utf8';
    let cipherEncoding = 'base64';
    let cipherChunks = [];
    let algorithm = 'aes-128-cbc'
    switch(key.length) {
        case 16:
            algorithm = 'aes-128-cbc'
            break;
        case 32:
            algorithm = 'aes-256-cbc'
            break;
    }
    let cipher = Crypto.createCipheriv(algorithm, key, iv);

    cipher.setAutoPadding(true);
    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(cipherEncoding));

    return cipherChunks.join('');
}

function getParamsAesStr(params) {
  let paramsArr = Object.keys(params).map(key => `${key}=${params[key]}`)
  paramsArr = paramsArr.sort()

  let signStr = Buffer.from(paramsArr.join('').toLowerCase(), 'utf-8').toString()
  let sign = Crypto.createHmac('md5', config.secret).update(signStr).digest('hex')
 
  let paramsStr = `${paramsArr.join('&')}&sign=${sign}`
  
  let paramsAesStr = enCryptoAes(paramsStr, config.secret.slice(0, 16), config.iv)
  paramsAesStr = Buffer.from(paramsStr, 'utf-8').toString('base64')
  return paramsAesStr
}

请找到可用的 Python 解密代码

from Crypto.Cipher import AES
import requests
import base64
import json
from urllib.parse import urlencode
import hashlib
import hmac


BLOCK_SIZE = 16
pad_fn = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
unpad_fn = lambda s: s[:-ord(s[len(s) - 1:])]


appkey = "app"
secret = bytes.fromhex("XXXXXXXXXXXXXXXXXXXXXXXXXXXX")
secret_Str  = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"

issueTypeId_Bug = 10201
issueTypeId_Task = 10002


def hmac_md5(key, msg):
    return hmac.new(key, msg, hashlib.md5).hexdigest()

def process_aes_key(key):
    if key is None:
        return None
    length = 16
    if len(key) == length:
        return key

    if len(key) > 16:
        return key[0:16]
    else:
        padding_count = 16 - len(key)
        xs = bytearray(key)
        for i in range(padding_count):
            xs.append(0)

        return bytes(xs)


if __name__ == '__main__':
    bug_info = {
        "pageNo":1,
        "pageSize":10
    }

    param_list = []
    for key in bug_info:
        param_list.append("{0}={1}".format(key, bug_info.get(key)))

    param_list.sort()
    all_str = "".join(param_list)
    all_str = all_str.lower()

    params_bytes = bytes(all_str, encoding="UTF-8")
    secret_bytes = bytes(secret_Str, encoding="UTF-8")
    #
    # 32 bits. secret
    sign = hmac_md5(secret_bytes, all_str.encode('utf-8'))
    bug_info['sign'] = sign

    # 16 bits. secret
    cryptor = AES.new(process_aes_key(secret), AES.MODE_CBC, "XXXXXXXXXXXXXXXX".encode("utf-8"))
    request_praram = urlencode(bug_info)
    encrypt_text = cryptor.encrypt(pad_fn(request_praram))

    base_encode_bytes = base64.b64encode(encrypt_text)
    final_param_str = base_encode_bytes.decode('utf-8')

    # final_p = {
    #    "appkey": "xxx",
    #    "param": final_param_str
    # }

    # s = session.post(create_bug_url, headers=request_headers, data=final_p, allow_redirects=True)

    # print(s.status_code, s.text)

预期的密文为: "6lzGZRetu2vccBJOftXKl0MXPNjOLYuu/4OK8NFNCkFIkZ1LnaZq2CApYQGk2V5tiAEk3EHY5S+QiWE/Qc6CHA=="

ps:我不确定它是否可以被 Python 代码复制,这是 Python 代码作者提供的演示。

Node的密文为: "cGFnZU5vPTEmcGFnZVNpemU9MTAmc2lnbj1kMzBhZGI0MGUxM2RlYTQzYzEzMDhkOTAzZTJkOWFjMw=="

getParamsAesStr({pageNo: 1, pageSize: 10})

我收到了不同的加密文本。我无法在 NodeJs 中获得与在 Python 中相同的结果。 我不熟悉 Python。我的 NodeJs 代码有什么问题?

你能帮我解决这个问题吗。

0 个答案:

没有答案