如何在 Node JS 中编写这个 Java 加密函数的等价物

How to write the equivalent of this Java encryption function in the Node JS

这是java

中用来加密的函数
 public static String encryptionFunction(String fieldValue, String pemFileLocation) {
    try {

        // Read key from file
        String strKeyPEM = "";
        BufferedReader br = new BufferedReader(new FileReader(pemFileLocation));
        String line;
        while ((line = br.readLine()) != null) {
            strKeyPEM += line + "\n";
        }
        br.close();
        String publicKeyPEM = strKeyPEM;
        System.out.println(publicKeyPEM);
        publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
        publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "").replaceAll("\s", "");;
        byte[] encoded = Base64.getDecoder().decode(publicKeyPEM);
        // byte[] encoded = Base64.decode(publicKeyPEM);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey pubKey = (PublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] cipherData = cipher.doFinal(fieldValue.getBytes());
        if (cipherData == null) {
            return null;
        }
        int len = cipherData.length;
        String str = "";
        for (int i = 0; i < len; i++) {
            if ((cipherData[i] & 0xFF) < 16) {
                str = str + "0" + java.lang.Integer.toHexString(cipherData[i] & 0xFF);
            } else {
                str = str + java.lang.Integer.toHexString(cipherData[i] & 0xFF);
            }
        }
        return str.trim();

    } catch (Exception e) {
        System.out.println("oops2");
        System.out.println(e);

    }
    return null;
}

我想要 javascript/Nodejs 中的等效项,我试过这个:

import * as NodeRSA from 'node-rsa';

private encryptionFunction(fieldValue: string , pemkey: string) : string {
    const rsa  = new NodeRSA(pemkey);
    const encrypted= rsa.encrypt(fieldValue , 'hex')
    return encrypted

}

但是两个函数的输出大小是一样的,但是显然加密类型是错误的。

Node-RSA 默认应用 OAEP (here) 作为填充,因此必须明确指定 Java 代码中使用的 PKCS#1 v1.5 填充。这必须在密钥导入之后和加密之前添加:

rsa.setOptions({ encryptionScheme: 'pkcs1' });

或者,可以在密钥导入期间直接指定填充:

const rsa  = new NodeRSA(pemkey, { encryptionScheme: 'pkcs1' });

通过这次更改,两个代码在功能上是相同的。


关于测试:请记住 RSA 加密不是确定性的,即给定 相同的输入 (密钥,明文),每个加密提供 不同的密文。因此,即使输入相同,两个(功能相同)代码的密文也会不同。所以这不是错误,而是预期的行为。
那么如何证明这两个代码的等价性呢?例如。通过使用 same code/tool.

解密两个密文