当前位置: 首页 > 工具软件 > Node-V2 > 使用案例 >

Node-rsa 使用公钥私钥加密解密

蒙勇
2023-12-01

Node-rsa 的加密解密格式模式是 pkcs1_oaep, 我使用的是pkcs1
 java 端处理加密数据模式的格式是pkcs1 , 为了兼容能够和java 服务器的格式相对应,建议使用pkcs1

let privateKey = 
"-----BEGIN PRIVATE KEY-----" + 
'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIXawhnxuqzgnwam' + 
'IHZ94tpqTsQtmWIUIVidPCkRN+vJXk8k7o2dUDHSY5w0Ls6MeNUPDxW2ED90yrop' + 
'YPhXTlT1caRaeINa4bOB6zaKymXNvpZdDbf+CR1dKWSAfTkUgKm+Pxi3EKRidP9D' + 
'lLRkKQEgLdUMQmmbSDXW3bmfWjiJAgMBAAECgYEAg/o/q6kGMHKBGeMu2uYgiM6M' + 
'vy1esK+8eUz/Blbt1lQD4vE9LPBRI+6XPGrPQ+SJNznT28pZltenE4q9C9+5YOM3' + 
'9Z+UU2tpAKaymOR8L/3VTeFrfd2iRi+gM7TWpXeM7jdEUfyY3dAQVDjZkHSrBnKC' + 
'n51u9YA4fI/DyiI1XAECQQDhjo+nastsDCu6c9Hcj4KAtt39+mou/Hz4ZnTP5Avc' + 
'8K5nERTy1LoyML+VUYu7hSFH5V2BNsOHSMCYmVuXl9zBAkEAl+uywk53HKdqWj57' + 
'ATNVvWFN5o2/mfosZuxMrwcxbHM8fp7pWppGJRYDmaNqhppWiFrHFDLl46QQu5dr' + 
'9bYlyQJBALpoaUyBNBDdlh4Hrf7ME5xwhNJra+nc/SME+bD91NgJiPjg4yE0sZTd' + 
'ONgchpC5G6Ihar9pFPrvI0x6IXoNJYECQBGFvwWIVVa5vJuSD0/xIteIDJsmCE5z' + 
'O4HXiXS6qKmwlO6p15J6rtKCOoITBitmS8rIZaPfxwI9nyxz56DclHkCQEH04rGr' + 
'qeIBSDAzuJt7+KhplTSeHsuTZfkw0RZBx6+rrEn9wsEuj9rB+j78LPU1665VNF5z' + 
'jZIkl4lnJi0Ij6k=' + 
"-----END PRIVATE KEY-----";
let publicKey = 
'-----BEGIN PUBLIC KEY-----' + 
'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCF2sIZ8bqs4J8GpiB2feLaak7E' + 
'LZliFCFYnTwpETfryV5PJO6NnVAx0mOcNC7OjHjVDw8VthA/dMq6KWD4V05U9XGk' + 
'WniDWuGzges2isplzb6WXQ23/gkdXSlkgH05FICpvj8YtxCkYnT/Q5S0ZCkBIC3V' + 
'DEJpm0g11t25n1o4iQIDAQAB' + 
'-----END PUBLIC KEY-----';

// 使用公钥加密:
let _data = this.encryptByPublicKey(publicKey, '1221');
// 使用私钥解密
this.decryptByPrivateKey(privateKey, _data);

// 使用私钥加密:
let _data = this.encryptByPrivateKey(privateKey, '1221');
// 使用公钥解密
this.decryptByPublicKey(publicKey, _data);

// Node-rsa 的加密解密格式模式是 pkcs1_oaep, 我使用的是pkcs1
// java 端处理加密数据模式的格式是pkcs1 , 为了兼容能够和java 服务器的格式相对应,建议使用pkcs1



/**
 * 手牌解密 使用私钥
 * @param txt 
 * @returns 
 */
public decryptByPrivateKey(privateKey: string, data: any) {
    const key = new NodeRSA(privateKey);
    key.setOptions({encryptionScheme: 'pkcs1'})
    let _data = key.decrypt(data, 'buffer');
    _data = this.Uint8ArrayTostring(_data);
    console.error("-----decryptMsg By PrivateKey: ", _data)
    return _data;
}
/**
 * 手牌解密 使用公钥
 * @param txt 
 * @returns 
 */
public decryptByPublicKey(publicKey: string, data: any) {
    const key = new NodeRSA(publicKey);
    key.setOptions({encryptionScheme: 'pkcs1'})
    let _data = key.decryptPublic(data, 'buffer');
    _data = this.Uint8ArrayTostring(_data);
    console.error("-----decryptMsg By publicKey: ", _data)
    return _data;
}

/**
 * 手牌加密 使用公钥
 * @param publicKey 
 * @param data 
 * @returns 
 */
public encryptByPublicKey(publicKey: string, data) {
    const key = new NodeRSA(publicKey);
    key.setOptions({encryptionScheme: 'pkcs1'})
    let _data = key.encrypt(data, 'buffer');
    console.error("-----encryptMsg By PublicKey: ", _data)
    return _data;
}
/**
 * 手牌加密 使用私钥
 * @param publicKey 
 * @param data 
 * @returns 
 */
public encryptByPrivateKey(privateKey: string, data) {
    const key = new NodeRSA(privateKey);
    key.setOptions({encryptionScheme: 'pkcs1'})
    let _data = key.encryptPrivate(data, 'buffer');
    console.error("-----encryptMsg By PrivateKey: ", _data)
    return _data;
}


// Uint8Array 转 string
private Uint8ArrayTostring(string: string, options = { stream: false }) {

    if (options.stream) {
        throw new Error(`Failed to encode: the 'stream' option is unsupported.`);
    }
    let pos = 0;
    const len = string.length;
    const out = [];
    let at = 0;  // output position
    let tlen = Math.max(32, len + (len >> 1) + 7);  // 1.5x size
    let target = new Uint8Array((tlen >> 3) << 3);  // ... but at 8 byte offset
    while (pos < len) {
        let value = string.charCodeAt(pos++);
        if (value >= 0xd800 && value <= 0xdbff) {
            // high surrogate
            if (pos < len) {
                const extra = string.charCodeAt(pos);
                if ((extra & 0xfc00) === 0xdc00) {
                    ++pos;
                    value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
                }
            }
            if (value >= 0xd800 && value <= 0xdbff) {
                continue;  // drop lone surrogate
            }
        }
        // expand the buffer if we couldn't write 4 bytes
        if (at + 4 > target.length) {
            tlen += 8;  // minimum extra
            tlen *= (1.0 + (pos / string.length) * 2);  // take 2x the remaining
            tlen = (tlen >> 3) << 3;  // 8 byte offset
            const update = new Uint8Array(tlen);
            update.set(target);
            target = update;
        }
        if ((value & 0xffffff80) === 0) {  // 1-byte
            target[at++] = value;  // ASCII
            continue;
        } else if ((value & 0xfffff800) === 0) {  // 2-byte
            target[at++] = ((value >> 6) & 0x1f) | 0xc0;
        } else if ((value & 0xffff0000) === 0) {  // 3-byte
            target[at++] = ((value >> 12) & 0x0f) | 0xe0;
            target[at++] = ((value >> 6) & 0x3f) | 0x80;
        } else if ((value & 0xffe00000) === 0) {  // 4-byte
            target[at++] = ((value >> 18) & 0x07) | 0xf0;
            target[at++] = ((value >> 12) & 0x3f) | 0x80;
            target[at++] = ((value >> 6) & 0x3f) | 0x80;
        } else {
            continue;
        }
        target[at++] = (value & 0x3f) | 0x80;
    }
    return target.subarray(0, at);;
}

 类似资料: