从 Java 加密密码 RSA 公钥 NodeJS

问题描述

我需要使用 Java 语言的公钥 RSA 在 NodeJS 中实现加密以加密 HttpPost 参数。

public class RSAUtil {
    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(key.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }        
    public static String encrypt(String publicKeyFrom,byte[] waitEncrypt) throws Exception {
        String publicK = publicKeyFrom.replaceAll("\\r\\n","");
        PublicKey publicKey = getPublicKey(publicK);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(1,publicKey);
        int inputLen = waitEncrypt.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;        
        for (int i = 0; inputLen - offSet > 0; offSet = i * 117) {
            byte[] cache;
            if (inputLen - offSet > 117) {
                cache = cipher.doFinal(waitEncrypt,offSet,117);
            } else {
                cache = cipher.doFinal(waitEncrypt,inputLen - offSet);
            }        
            out.write(cache,cache.length);
            ++i;
        }        
        byte[] encryptedData = out.toByteArray();
        out.close();
        return Base64.encodeBase64String(encryptedData);
    }
}

这里是如何在 Java 中使用它。

String PUBLIC_KEY = "MIIBIjANxxxxxxxxlGqQIDAQAB";
String reqParams = "{\"code\":\"A12345\"}";
String encryptedParams = RSAUtil.encrypt(PUBLIC_KEY,reqParams.getBytes());

我已经尝试将代码翻译成 NodeJS,如下所示。

const Crypto = require('crypto');
const encryptParams = function (params,publicKey) {
    const buffer = Buffer.from(params)
    const encrypted = Crypto.publicEncrypt(publicKey,buffer)
    const ecryptedParams = encrypted.toString('base64');
    return ecryptedParams;
}

const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MIIBIjANxxxxxxxxlGqQIDAQAB
-----END PUBLIC KEY-----`;
const reqParams = { code: 'A12345' };
const encryptedParams = encryptParams(JSON.stringify(reqParams),PUBLIC_KEY);

但是只要我把NodeJS代码的encrptedParams改成现有的Java代码HttpPost就行不通。如果我使用 encrptedParams 从 Java 到 NodeJS Axios,它就可以工作。

你能帮我指出我的 NodeJS 代码有什么问题吗?或者告诉我从上面的 Java 代码加密到 NodeJS 代码的正确方法

谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)