RSA/ECB/PKCS 1 Padding Java加密-与node.js等效的问题

lsmd5eda  于 2023-03-22  发布在  Node.js
关注(0)|答案(1)|浏览(232)

我正在构建一个node.js应用程序,需要将一些加密数据发送到服务器。这些数据必须使用给定的公钥(.pem格式)加密。使用下面的java代码,我能够成功加密数据,但是当在node.js上使用类似的代码时,加密数据被服务器视为无效。我也尝试使用node-rsa,但没有太多运气:
有人遇到过这种问题吗?
先谢了!
Java代码示例:

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
cipher.init(Cipher.ENCRYPT_MODE, publicKeys);
byte[] encryptedText = cipher.doFinal(textToEncrypt.getBytes());
String encryptedTextFinal = Base64.encodeBase64String(encryptedText);
return encryptedTextFinal;

Same code on Node.js:

function encryptWithPubKey(dataToEncrypt) {
 const absolutePath = path.resolve(publicKeyPath)
 const pubKey = fs.readFileSync(absolutePath, 'utf8')
 const buffer = Buffer.from(dataToEncrypt, 'base64')
 const encrypted = crypto.publicEncrypt({key: pubKey, padding: crypto.constants.RSA_PKCS1_PADDING}, buffer)
 return encrypted.toString('base64')
}
bpzcxfmw

bpzcxfmw1#

解决您的问题:

Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKeys);
        byte[] encryptedText = cipher.doFinal(textToEncrypt.getBytes());
        String encryptedTextFinal = Base64.encodeBase64String(encryptedText);
        return encryptedTextFinal;

        Same code on Node.js:

        function encryptWithPubKey(dataToEncrypt) {
        const absolutePath = path.resolve(publicKeyPath)
        const pubKey = fs.readFileSync(absolutePath, 'utf8')
        const buffer = Buffer.from(dataToEncrypt, 'base64')
        const encrypted = crypto.publicEncrypt({key: pubKey, padding: crypto.constants.RSA_NO_PADDING}, buffer)
        return encrypted.toString('base64')
        }

更简单的代码:创建一个没有填充的密码。不要在生产环境中使用。

import javax.crypto.Cipher;
        import java.io.*;
        import java.nio.charset.StandardCharsets;
        import java.security.*;
        import java.util.Base64;

        public class Main {

            public static void main(String[] args) throws Exception {

                // Generate a new RSA key pair
                KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
                keyPairGenerator.initialize(2048);
                KeyPair keyPair = keyPairGenerator.generateKeyPair();

                // Get the private key as a string
                PrivateKey privateKey = keyPair.getPrivate();
                System.out.println("Private Key");
                System.out.println(Base64.getEncoder().encodeToString(privateKey.getEncoded()));

                // Get the public key as a string
                PublicKey publicKey = keyPair.getPublic();
                System.out.println("Public Key");
                System.out.println(Base64.getEncoder().encodeToString(publicKey.getEncoded()));

                // Encrypt the message using the private key
                String message = "Hello, World!";
                Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
                cipher.init(Cipher.ENCRYPT_MODE, privateKey);
                byte[] encryptedMessage = cipher.doFinal(message.getBytes());

                // Transmit the encrypted message and the public key string to the Node.js side
                System.out.println("Encrypted message: " + Base64.getEncoder().encodeToString(encryptedMessage));
            }
        }

在NodeJs中你可以使用解密而不用填充。

const crypto = require('crypto')
        publicKeyString = '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkpcXDapUKExVugabuetO+XUuhqQtBaWx1rlvgDI/BIwIFcf21phzM1H1qc/yXFF6mn8k4pM+E8iJeD7BAPKXbVeYpjH/6Lj21IGOe95wO664jX6/AAHB9FyBHglMEnMCXQQPxMPcVh4f9gcYhSuJnzmnH05Ryp3NS68fYGBODKwPld01K8lfnIuisvasytR+7ALGeDrB0LXQfqw48xoaXtbv627XxI6PyeJTPRdRQuCo3h6Fc6Q6KPhXf7ZlXBtgftTfu457svT7uQXHnWy6SsGz/rj229RatR7G/olV22atyqT9dS+RiXdlC/j8sDZt/OQL7VGme6X3V2759wZBZQIDAQAB\n-----END PUBLIC KEY-----'
        publicKey = crypto.createPublicKey({key: Buffer.from(publicKeyString)})
        encrypted_msg = 'EUQBSw4H+J3ZqKskrq8kfmXDQiURsFXsfAuIH8bRYo4k0Ke1E2QD8WrAAIOmtum5KHYXcfxfDK3krWZepyjWO1hsva6e8efyOR7UL8nJhD/fzxLzihkB5pdTPUf8sCKyrQ6aZS6rLghTabWjVyzXuwPB7PY/pk68cCstxyLy+WwNFcXcPHnhypMux9EZK++kffpcUyfBG18ucTq+XdTMAsP/ongBJi9ImjE6lDorvfKgVRYkN+WhWHXe0izPCrz4cG68gvyn0ypmdGi33Amk8s40o7E5msB5e+qszpG+wN2xr04wcvELx5CwrMWU5Jh3xJOGM+SNWdrz/3m+xUf3MA=='
        output = crypto.publicDecrypt({key: publicKey, padding: crypto.constants.RSA_NO_PADDING}, Buffer.from(encrypted_msg, 'base64'))
        console.log(String(output))

相关问题