如何在节点JS中编写此Java加密函数的等效词

发布于 2025-02-01 11:56:24 字数 2074 浏览 2 评论 0原文

这是用于在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

}

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

This is the function used to encrypt in 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;
}

I want the equivalent of this in javascript/Nodejs, i tried this:

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

}

But the output size of both functions is the same, but apparently the encryption type is wrong.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三月梨花 2025-02-08 11:56:24

node-rsa应用OAEP(在这里)默认为padding #1 V1.5必须明确指定Java代码中使用的填充物。必须在密钥导入和加密之前添加:

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

或者,可以在关键导入期间直接指定填充物:

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

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


关于测试:请记住,RSA加密不是确定性的,IE给定相同的输入(键,明文),每个加密提供了不同的ciphertext 。因此,即使输入是相同的,两种(功能相同)代码的密文也将有所不同。因此,这不是一个错误,而是预期的行为。
那么如何证明这两个代码的等效性呢?例如,使用相同代码/工具将两个密文解密。

Node-RSA applies OAEP (here) as padding by default, so the PKCS#1 v1.5 padding used in the Java code must be explicitly specified. This has to be added after key import and before encryption:

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

Alternatively, the padding can be specified directly during key import:

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

With this change, both codes are functionally identical.


Regarding testing: Keep in mind that RSA encryption is not deterministic, i.e. given the same input (key, plaintext), each encryption provides a different ciphertext. Therefore, the ciphertexts of both (functionally identical) codes will be different even if the input is identical. So this is not a bug, but the expected behavior.
How then can the equivalence of both codes be proved? E.g. by decrypting both ciphertexts with the same code/tool.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文