node-rsa和java-rsa相对应的加解密及rsa公私钥生成

和第三方对接, 有可能语言不一样, 对应的加解密方法也会有所差别, 本篇记录RSA加解密在java在node分别如何实现可以实现互通加解密方法,Talk is cheap , show you the code:

***注意!!!  ssl生成密钥的时候,Java使用的是pkcs8.pem格式的密钥, 而我们其他语言则直接使用private.pem格式就可以

附上ssl密钥生成bash:

OpenSSL> genrsa -out rsa_private_key.pem   1024  #生成私钥
OpenSSL> pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out rsa_private_key_pkcs8.pem #Java开发者需要将私钥转换成PKCS8格式
OpenSSL> rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem #生成公钥
OpenSSL> exit #退出OpenSSL程序

在java中我们使用hex也就是16进制的密钥进行加解密:

//公钥加密方法如下
public static String encryptByPublicKey(String content, String key) throws Exception {
        byte[] keyBytes = ConvertUtil.hexStrToBytes(key);
        byte[] data = content.getBytes("UTF-8");
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(1, publicKey);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;

        byte[] cache;
        for(int i = 0; inputLen - offSet > 0; offSet = i * 117) {
            if (inputLen - offSet > 117) {
                cache = cipher.doFinal(data, offSet, 117);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }

            out.write(cache, 0, cache.length);
            ++i;
        }

        cache = out.toByteArray();
        out.close();
        return ConvertUtil.bytesToHexStr(cache);
    }
//私钥解密方法如下
public static String decryptByPrivateKey(String content, String key) throws Exception {
        byte[] keyBytes = ConvertUtil.hexStrToBytes(key);
        byte[] data = ConvertUtil.hexStrToBytes(content);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(2, privateKey);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;

        byte[] cache;
        for(int i = 0; inputLen - offSet > 0; offSet = i * 128) {
            if (inputLen - offSet > 128) {
                cache = cipher.doFinal(data, offSet, 128);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }

            out.write(cache, 0, cache.length);
            ++i;
        }

        cache = out.toByteArray();
        out.close();
        return new String(cache, 0, cache.length, "UTF-8");
    }

那么对应的node中我们可以这样写,就可以加解密对应的java代码生成的加密内容了:

//加密
function encrypt(msg) {
    try {
        const public_key = fs.readFileSync(path.join(__dirname, '/certs/xxxx_public_key.pem'), 'utf8');
        const encryptStr = crypto.publicEncrypt({
            key: public_key,
            padding: crypto.constants.RSA_PKCS1_PADDING
        }, Buffer.from(msg,'utf8'))
        return encryptStr.toString('hex');
    } catch (e) {
        console.log(e);
        return false;
    }
}

//解密 解密我们使用node-rsa,因为crypto所支持的解密密文长度有限,需要自己转换否则可能报错
function decrypt(msg) {
    try {
        let private_key = fs.readFileSync(path.join(__dirname, '/certs/xxxx_private_key.pem'), 'utf8');
        var privatedecrypt= new NodeRSA(private_key,{encryptionScheme: 'pkcs1'});
        var decrypted = privatedecrypt.decrypt(Buffer.from(msg,'hex'), 'utf8',);
    } catch (e) {
        console.log(e);
        return false;
    }
}

是不是很简单呢? 但是当时因为长度问题确实是费了一番功夫的 0..0

感谢您的阅读!如果文章中有任何错误,或者您有更好的理解和建议,欢迎和我联系!

你可能感兴趣的:(node-rsa和java-rsa相对应的加解密及rsa公私钥生成)