这是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中实现这一点,我try 了以下方法:

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 input(密钥,明文),每个加密提供different ciphertext.因此,即使输入相同,两个(功能相同)代码的密文也会不同.所以这不是一个bug,而是预期的行为

Javascript相关问答推荐

Bootstrap动态选项卡在切换选项卡后保持活动状态,导致元素堆叠

手机上的渲染错误文本必须在文本组件中渲染,但在浏览器上没有问题<><>

单个HTML中的多个HTML文件

React.Development.js和未捕获的ReferenceError:未定义useState

如何在ASP.NET项目中使用Google Chart API JavaScript将二次轴线值格式化为百分比

在Java中寻找三次Bezier曲线上的点及其Angular

为什么JPG图像不能在VITE中导入以进行react ?

MongoDB受困于太多的数据

Google脚本数组映射函数横向输出

当从其他文件创建类实例时,为什么工作线程不工作?

处理TypeScrip Vue组件未初始化的react 对象

如何根据输入数量正确显示alert ?

Reaction即使在重新呈现后也会在方法内部保留局部值

不协调嵌入图片

按特定顺序将4个数组组合在一起,按ID分组

Promise.race()返回已解析的promise ,而不是第一个被拒绝的promise

如何在加载页面时使锚定标记成为焦点

如何缩小函数中联合返回类型的范围

Playwright:ReferenceError:browserContext未定义

在openstreemap/leaflet中,当鼠标在 map 上移动时,如何在小工具提示中实时显示坐标