Search code examples
javanode.jsnode-modulespublic-key-encryptionforge

RSA Public Key to Node-Forge Public Key


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 ?


Solution

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