and node-rsa java-rsa corresponding public and private key encryption and decryption and generated rsa

And third-party docking, it may not be the same language, the corresponding encryption method will be different herein, this record RSA encryption in java node, respectively, how to achieve interoperability encryption method can be implemented, Talk is cheap, show you the code in :

*** NOTE !!! ssl key generation time, Java is the use of a key pkcs8.pem format, and we use other languages ​​directly private.pem format can be

Attach ssl key generation 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程序

In java we use the hex is hex key for encryption and decryption:

//公钥加密方法如下
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");
    }

Then the corresponding node, we can write, you can encrypt and decrypt the encrypted content generated java code corresponding to the:

//加密
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;
    }
}

Is not it simple? But it was not the length of the problem is really spent a lot of effort 0..0

Thank you for reading! If there are any errors in the article, or if you have a better understanding and suggestions, please contact me!

Published 29 original articles · won praise 18 · views 30000 +

Guess you like

Origin blog.csdn.net/Baby_lucy/article/details/89669202