RSA Public Node-Forge 密钥 Public 密钥

RSA Public Key to Node-Forge Public Key

我需要有关 NodeJS 代码的帮助。我将为以下 JAVA 代码编写 nodejs 代码。

String rsaPublicKey = "...";
String data = "...";

X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(rsaPublicKey.getBytes()));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
publicKey = keyFactory.generatePublic(keySpec);

Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] bytes = cipher.doFinal(data.getBytes("UTF-8"));

我尝试使用“Forge”,但不知道如何将给定的 RSA Public 密钥转换为 Forge Public 密钥。 谁能帮我解决这个问题?

正如我在评论中提到的,我并不是要使用常规 string-conversion,而是从编码的 publicKey 到 PEM-format.

的转换

由于您没有发布示例 public 密钥,我在下面的示例代码中生成了一个新的 RSA 密钥对,并使用非常简单的方法将其转换为 PEM-format。对 RSAPublicKey 的转换只是为了显示模数和指数 生成的密钥。

请记住,该代码没有任何异常处理,仅用于教育目的。

您可以使用 public 密钥作为 node.js 密钥导入的来源

var publicKey = pki.publicKeyFromPem(pem);

结果如下:

publicKeyBase64:
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApDkozwJFhmpDCW8yIlZMoDLHG0zS+o0hHHQHDNmLgn8AWWSHNsO5LJqhJWAxccc1FbE6LKBgLXDvpSIOyHtvzpmlFdQxK32hj7Bl49BuXhypHX2TShDD44Kgfn6WUM/jr31UagalcZkdhe3KjJqf8mMbhZnUNef+twu+MecfO9ruh3dY8LtrqLz2wS6RGwZHlCEO+bFE8sZseLBtnTWhrqgndtw1GkvwyzGzDWFYSgv90cAYWSxWeRsGawBuKSwryDkMYY/h9EvEK50uKP3UVFUXbnZnyGclF1Fv9X5RkggmhO7Vf3bYA04sEJjZherZhA/xvHEX0xnbLfu0S/8w1QIDAQAB

publicKeyInPemFormat:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApDkozwJFhmpDCW8yIlZM
oDLHG0zS+o0hHHQHDNmLgn8AWWSHNsO5LJqhJWAxccc1FbE6LKBgLXDvpSIOyHtv
zpmlFdQxK32hj7Bl49BuXhypHX2TShDD44Kgfn6WUM/jr31UagalcZkdhe3KjJqf
8mMbhZnUNef+twu+MecfO9ruh3dY8LtrqLz2wS6RGwZHlCEO+bFE8sZseLBtnTWh
rqgndtw1GkvwyzGzDWFYSgv90cAYWSxWeRsGawBuKSwryDkMYY/h9EvEK50uKP3U
VFUXbnZnyGclF1Fv9X5RkggmhO7Vf3bYA04sEJjZherZhA/xvHEX0xnbLfu0S/8w
1QIDAQAB
-----END PUBLIC KEY-----

modulus:  20731268369385753286263425327135051982140722030090056263956156187995595756162638067632049766572173871222899673059402693752671732595103415705071364110163930779801384635600704353948134714995032771402672253081803951568749471153442310395557466672145372102367812045909635515067251201801481045420809949678999367006984696717741160391651530870395354801871215718392636783213332400044611988145616424335265196351536718900512088911138715764629635492725732261535350636958727512114194585140879639939102048063723080960259912864453126601881542413439087477332229964312815604341576075763616064453908632786205270096882928322048256061653
exponent: 65537

代码:

import java.security.*;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;

public class Main {

    private static final String X509_PEM_HEADER = "-----BEGIN PUBLIC KEY-----";
    private static final String X509_PEM_FOOTER = "-----END PUBLIC KEY-----";
    public final static String LINE_SEPARATOR = System.getProperty("line.separator");

    public static void main(String[] args) throws NoSuchAlgorithmException {
        System.out.println("RSA Public Key to Node-Forge Public Key");

        // rsa key generation
        KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
        kpGen.initialize(2048, new SecureRandom());
        KeyPair keyPair = kpGen.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        String publicKeyBase64 = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        System.out.println("publicKeyBase64:\n" + publicKeyBase64);

        // encode public key to PEM format
        String publicKeyInPemFormat = formatPublicKey(Base64.getDecoder().decode(publicKeyBase64));
        System.out.println("\npublicKeyInPemFormat:\n" + publicKeyInPemFormat);

        // casting to RSAPublicKey to get the modulus & exponent of the key
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        System.out.println("\nmodulus:  " + rsaPublicKey.getModulus() + " \nexponent: " + rsaPublicKey.getPublicExponent());
    }

    public static String formatPublicKey(byte[] encodedKey)  {
        final Base64.Encoder encoder = Base64.getMimeEncoder(64, LINE_SEPARATOR.getBytes());
        final String encodedText = new String(encoder.encode(encodedKey));
        final String prettified_key = X509_PEM_HEADER + LINE_SEPARATOR + encodedText + LINE_SEPARATOR + X509_PEM_FOOTER;
        return prettified_key;
    }
}
    const forge = require('node-forge');
    const fs = require('fs');
    
    const dataToEncrypt = 'FFAA1A2308991DAE...' // Hex string

    async function encrypt(dataToEncrypt){
      try{
           const data = await fs.readFile('x509/certifictate/path/certificate.cer', 'utf8');
           const certPem = forge.pki.certificateFromPem(data);
           // console.log('public key-----', certPem.publicKey.n.toString(16));
           const encryptedData = certPem.publicKey.encrypt(forge.util.hexToBytes(dataToEncrypt), 'RSAES-PKCS1-V1_5');
           return forge.util.createBuffer(encryptedData).toHex();
      } catch(error){
          console.log(error);
      }
    }