RSA公钥转换为Node-Forge公钥

huangapple go评论77阅读模式
英文:

RSA Public Key to Node-Forge Public Key

问题

我需要帮助关于Node.js代码。我将为下面的JAVA代码编写Node.js代码。

const rsaPublicKey = "...";
const data = "...";

const keySpec = new NodeRSA.X509Certificate();
keySpec.publicKey = rsaPublicKey;

const key = new NodeRSA({b: 512}); // You can adjust the key size
key.importKey(keySpec.exportPublicKey(), 'pkcs1-public-pem');

const encryptedData = key.encrypt(data, 'base64');

我尝试使用"Forge"库,但不知道如何将给定的RSA公钥转换为Forge公钥。
有人能帮我解决这个问题吗?

英文:

I need help with NodeJS Code. I am going to write nodejs code for below JAVA code.

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"));

I tried using "Forge" but don't know how to convert given RSA Public key to Forge Public Key.
Can anyone help me with this ?

答案1

得分: 1

按照您的要求,我将为您提供翻译好的代码部分:

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公钥转换为Node.js Forge公钥");

        // 生成RSA密钥对
        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);

        // 将公钥编码为PEM格式
        String publicKeyInPemFormat = formatPublicKey(Base64.getDecoder().decode(publicKeyBase64));
        System.out.println("\npublicKeyInPemFormat:\n" + publicKeyInPemFormat);

        // 转换为RSAPublicKey以获取密钥的模数和指数
        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;
    }
}

请注意,我仅提供了代码的翻译,不包括其他额外内容。如果您需要进一步的帮助,请随时提问。

英文:

As I mentioned in my comment I do not mean to use a regular string-conversion but a conversion from encoded publicKey to PEM-format.

As you did not publish a sample public key I'm generating a new RSA keypair in my sample code below and convert it into PEM-format with a very simple method. The casting to RSAPublicKey is only good to show the modulus and exponent of the
generated key.

Please keep in mind that the code does not have any exception handling and is for educational purpose only.

You can use the public key as source for node.js key importing with

var publicKey = pki.publicKeyFromPem(pem);

Here are the results:

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

code:

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;
}
}

答案2

得分: 1

const forge = require('node-forge');
const fs = require('fs');

const dataToEncrypt = 'FFAA1A2308991DAE...'; // 十六进制字符串

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);
  }
}
英文:
    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);
}
}

huangapple
  • 本文由 发表于 2020年8月31日 20:45:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63671089.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定