nanxiafenglai
1
2025-05-22

加密代码

/**
 * 加密过程详细说明
 * 
 * 本文件详细说明了使用RSA+AES混合加密方案的完整实现过程
 */

const CryptoJS = require('crypto-js');
const NodeRSA = require('node-rsa');

/**
 * 第一步:准备原始数据
 * - 创建一个包含敏感信息的对象
 * - 添加时间戳以增加数据的唯一性
 */
const prepareOriginalData = () => {
    return {
        username: 'testuser',
        password: '123456',
        timestamp: new Date().getTime()
    };
};

/**
 * 第二步:生成RSA密钥对
 * - 使用2048位的密钥长度(安全性更高)
 * - 生成公钥和私钥对
 */
const generateRSAKeyPair = () => {
    const keyPair = new NodeRSA({b: 2048});
    return {
        publicKey: keyPair.exportKey('public'),
        privateKey: keyPair.exportKey('private'),
        keyPair: keyPair
    };
};

/**
 * 第三步:生成随机AES密钥
 * - 使用CryptoJS生成32字节(256位)的随机密钥
 * - 转换为字符串格式
 */
const generateAESKey = () => {
    return CryptoJS.lib.WordArray.random(32).toString();
};

/**
 * 第四步:使用RSA公钥加密AES密钥
 * - 使用RSA公钥加密AES密钥
 * - 输出base64编码的加密结果
 */
const encryptAESKey = (keyPair, aesKey) => {
    return keyPair.encrypt(aesKey, 'base64');
};

/**
 * 第五步:使用AES加密原始数据
 * - 将原始数据转换为JSON字符串
 * - 使用AES-256-ECB模式加密
 * - 使用PKCS7填充
 */
const encryptData = (data, aesKey) => {
    return CryptoJS.AES.encrypt(
        JSON.stringify(data),
        aesKey,
        {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        }
    ).toString();
};

/**
 * 执行完整的加密过程
 */
const performEncryption = () => {
    // 1. 准备原始数据
    const originalData = prepareOriginalData();
    console.log('1. 原始数据:', originalData);

    // 2. 生成RSA密钥对
    const { publicKey, privateKey, keyPair } = generateRSAKeyPair();
    console.log('2. RSA密钥对已生成');
    console.log('   公钥:', publicKey);
    console.log('   私钥:', privateKey);

    // 3. 生成AES密钥
    const aesKey = generateAESKey();
    console.log('3. AES密钥已生成:', aesKey);

    // 4. 加密AES密钥
    const encryptedKey = encryptAESKey(keyPair, aesKey);
    console.log('4. 加密后的AES密钥:', encryptedKey);

    // 5. 加密数据
    const encryptedData = encryptData(originalData, aesKey);
    console.log('5. 加密后的数据:', encryptedData);

    // 6. 返回最终结果
    const result = {
        'encrypt-key': encryptedKey,
        'data': encryptedData
    };
    console.log('6. 最终加密结果:', result);

    return {
        result,
        privateKey // 保存私钥用于解密
    };
};

// 执行加密过程
performEncryption();