我试图在 crypto-js 的帮助下使用密钥加密字符串,有两个问题,一是它总是生成相同的密钥,这不应该是每次都是唯一的,第二个问题是加密密钥的大小是比预期的时间长,我正在尝试打印这种格式和大小
GwJPNUfPXZZsuc0iqOFhn%2BYhMJKxXBUYl9g3iKqL8CE%3D
,其中始终包含 2% 的特殊字符。
尝试使用 sha256 进行加密并进行编码并返回上述模式有任何帮助吗?
index.js
const CCrypto = require('crypto-js');
function encryptSHA256(data, secretKey) {
const secretKeyWordArray = CCrypto.enc.Utf8.parse(secretKey);
return CCrypto.AES.encrypt(data, secretKeyWordArray, {
mode: CCrypto.mode.CBC,
padding: CCrypto.pad.Pkcs7,
iv: CCrypto.lib.WordArray.create([0]),
}).toString();
}
function generateEncryptedValue(paymentId, specialtyID, secretKey) {
const concatString = paymentId.toString() + "_" + specialtyID;
const encryptedResult = encryptSHA256(concatString, secretKey);
const base64Result = CCrypto.enc.Base64.stringify(CCrypto.enc.Utf8.parse(encryptedResult));
const percentEncodedResult = encodeURIComponent(base64Result);
return percentEncodedResult;
}
// Example usage
const paymentId = 15680298; // paymentId is a number
const specialtyID = '8018290';
const secretKey = "EiD0BVQle0xFjZvYOupQsXCWAcAwBaTjlZ7G7rryNos=";
const result = generateEncryptedValue(paymentId, specialtyID, secretKey);
console.log('Encrypted and Percent Encoded Result:', result);
几个问题:
恒定密钥:您使用恒定密钥(secretKey)进行加密。要每次生成唯一的密钥,您需要生成随机密钥或使用不同的密钥生成机制。
Base64 编码:您将加密结果编码为 Base64 两次(一次在加密时,一次在转换为 UTF-8 时)。您应该只执行一次 Base64 编码。
更新了以下代码修复示例:
const CCrypto = require('crypto-js');
function generateSecretKey() {
const keySize = 32; // 256 bits
return CCrypto.lib.WordArray.random(keySize).toString();
}
function encryptSHA256(data, secretKey) {
const secretKeyWordArray = CCrypto.enc.Utf8.parse(secretKey);
const encrypted = CCrypto.AES.encrypt(data, secretKeyWordArray, {
mode: CCrypto.mode.CBC,
padding: CCrypto.pad.Pkcs7,
iv: CCrypto.lib.WordArray.create([0]),
});
return encrypted.toString();
}
function generateEncryptedValue(paymentId, specialtyID, secretKey) {
const concatString = paymentId.toString() + "_" + specialtyID;
const encryptedResult = encryptSHA256(concatString, secretKey);
const percentEncodedResult = encodeURIComponent(encryptedResult);
return percentEncodedResult;
}
const paymentId = 15680298;
const specialtyID = '8018290';
const secretKey = generateSecretKey(); // Generate a random secret key
const result = generateEncryptedValue(paymentId, specialtyID, secretKey);
console.log('Encrypted and Percent Encoded Result:', result);