I solved it by writing a java class and imported into nodejs using node-java package.
Java package
package com.nearinfinity.nodeJava;
import java.io.*;
import java.util.Base64;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.*;
import javax.crypto.EncryptedPrivateKeyInfo;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class EncryptedPrivateKeyDecode {
public PrivateKey getPrivatekey(String [] args)
{
try {
if (args.length == 0) {
throw new NullPointerException("the encoded parameter " +
"must be non-null");
}
// Please change the path to your pem file
File f = new File(args[0]);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
String encrypted = new String(keyBytes);
String passphrase = new String(args[1]);
encrypted = encrypted.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "");
encrypted = encrypted.replace("-----END ENCRYPTED PRIVATE KEY-----", "");
EncryptedPrivateKeyInfo pkInfo = new EncryptedPrivateKeyInfo(Base64.getMimeDecoder().decode(encrypted));
PBEKeySpec keySpec = new PBEKeySpec(passphrase.toCharArray());
SecretKeyFactory pbeKeyFactory = SecretKeyFactory.getInstance(pkInfo.getAlgName());
PKCS8EncodedKeySpec encodedKeySpec = pkInfo.getKeySpec(pbeKeyFactory.generateSecret(keySpec));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey encryptedPrivateKey = keyFactory.generatePrivate(encodedKeySpec);
return encryptedPrivateKey;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Node code
const java = jinst.getInstance();
const EncryptedPrivateKeyDecode = java.import(
'com.nearinfinity.nodeJava.EncryptedPrivateKeyDecode'
);
const privateKey = new EncryptedPrivateKeyDecode().getPrivatekeySync([
privateKeyPath,
privateKeyPassphrase
]);
and now we can use this privateKey in node-jdbc package