Esempio n. 1
0
  /*
   * RSA数据/公钥加密
   * @params data 需要加密的数据
   * @params pubKey 公钥
   * */
  encryptRSA(data, pubKey) {
    // var encrypt = new JSEncrypt();
    // encrypt.setPublicKey(pubKey);
    // return encrypt.encrypt(data);

    const clientKey = new JSEncrypt(pubKey, 'public');
    clientKey.setOptions({
      encryptionScheme: 'pkcs1'
    });
    const encrypt = clientKey.encrypt(data, 'base64');

    return encrypt;


  }
Esempio n. 2
0
const callRSA = args => {
    // when passing through, `Buffer`-properties will become an Object --> we need to retransfer them:
    args = toBuffer(args);
    let fn = args[0],
        key = args[1],
        rsaKey, returnValue, privateKey, publicKey, format, options;
    const methodArgs = args.slice(2); // arguments to apply to any rsaKey-method

    if (fn==='generateKeyPair') {
        if ((typeof key!=='string') && !Buffer.isBuffer(key)) {
            key = null;
            format = args[1];
            options = args[2];
        }
        format || (format={});
        rsaKey = new NodeRSA(key);
        key || rsaKey.generateKeyPair(format.b, format.e);
        options && rsaKey.setOptions(options);

        try {
            privateKey = rsaKey.exportKey();
            publicKey = rsaKey.exportKey('public');
        }
        catch (err) {
            return {error: err.message};
        }
        return {
            value: {
                private: privateKey,
                public: publicKey
            }
        };
    }

    if (fn==='privateToPublicKey') {
        if ((typeof key!=='string') && !Buffer.isBuffer(key)) {
            return {error: 'No valid private key'};
        }
        format || (format={});
        rsaKey = new NodeRSA(key);
        try {
            publicKey = rsaKey.exportKey('public');
        }
        catch (err) {
            return {error: err.message};
        }
        return {
            value: publicKey
        };
    }

    if (Object.itsa_isObject(key)) {
        try {
            rsaKey = new NodeRSA(key.key, key.format, key.options);
        }
        catch (err) {
            return {error: err.message};
        }
    }
    else {
        try {
            rsaKey = new NodeRSA(key);
        }
        catch (err) {
            return {error: err.message};
        }
    }
    try {
        returnValue = rsaKey[fn].apply(rsaKey, methodArgs);
    }
    catch (err) {
        return {error: err.message};
    }
    // for some reasson, the boolean funcs don't return boolean values:
    // make them boolean:
    BOOLEAN_METHODS[fn] && (returnValue=!!returnValue);
    if (CRYPTED_METHODS[fn]) {
        try {
            returnValue = JSON.stringify(returnValue);
        }
        catch (err) {
            return {error: err.message};
        }
    }
    return {value: returnValue};
};