How to decrypt an encrypted RSA key .pem file with Node.js - node.js

I have an encrypted private key file (I also have the unencrypted one for comparison), assume that I have the password and I want the decrypted version of that file - I tried using the URSA module (npm install ursa) , but it is not suitable for my needs because it is not portable enough (requires a specific version of the .NET framework on Windows). I need a raw Node.js solution - Is there a module that would let me do this?
If not, what is the exact process for turning this encrypted key into a plain key?
I tried using Node.js' crypto module crypto.createDecipher(algorithm, password)... Using 'DES-EDE3-CBC' as the algorithm and my password, but I get giberrish output which doesn't match the unencrypted version of the key. I was running the decryption on the content starting with o5IM... and ending with ==... I also tried only the string from o5IM to OZDug and that didn't work either.
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,0DC77650897F6756
o5IMl6kanVn72mKmvlKHZhz+5YXZsnPvOVLOm9FATNLt/EC+YQgznIlxR3tHYbk/
6YXXS9YeyebJ0uvD0RG14q+zDrWSoE70VsiEDJVj6HUCBe3O7wjaZ6tPLIKXWXtU
Go315e0OCMszafWnWSO5EN8ZSpJSjHCa9b0nJTWu1gyA9Z21c5Gu/jwHi/3Fvk2x
YDAl17RaTSMk2enez8+oqSBre3PTuX+1DWnfZbEWCnWidioPkisfVj5+qkCQmpzV
9OyCZ09S+ygwtEJkG+GdJuIK0oAVK1J6Jlpns7n/b3vbxuV3FxIWJteicujffnom
c9bV63c/9enRJKLV/gU/6JzD1SnpwH8grU5Y7TqHg//eA9XtO1+7Rye/MRgCsEsX
lKLctmB2a7PQWV2Wm9sQhfjI+J0mikuBDIoUp16JIn3UKWGY7g9CRkqwM9ozgVBG
8IoPoKSE/Rys9AkIp0gvQ9HeVUAkMwzWV60D0uKImZEFxkZ1WCcBS8xLc+kWQfwm
Ngh0rpf3AtKIZcatWkTzmpFEcXwRSJDBH8PwJM9UpsOJHmb05UjN54MhyC/HaYV7
n0HToHlOipmOF0Z299/4rxQanVZjC2pfbVi2HbbhWEGlbUI728rhoDvfK1N2eHfy
edGz9Ls6hAMcYrTa4knIMQr5W7iXaTOYDPxSxgsddJfm6AkMo3f0Oaz3+IIpyr+S
UVTCAN3nubHVVWld4xNsqn55zeLLwt4R0MyqgFXeK5CDFN/R7YLnuCm//kV5ozHn
dd43mBt7FtEuAX0pjocXvlQOTjM8quBOtszEj+XkcpgvnjGCkOZDug==
-----END RSA PRIVATE KEY-----

Related

HTTPS in Nodejs - error:06065064 digital envelope routines evp_decryptfinal_ex bad decrypt

We tried to install our Hapis (Nodejs Version 14) Web service on our customer's server. It ran under HTTP for months, but when we went to enable HTTPS with the appropriate paths to the cert and key it fails when the service starts up with:
error:06065064:digital envelope routines:EVP_Decryptfinal_ex:bad decrypt
Their certificate and key are generated using the Venafi online portal. It gave them a crt and key. The crt uses a Signature algorithm: sha256RSA, Signature hash algorithm of sha256, and Thumbprint algorith: sha1.
Also, the private key is a RSA PRIVATE KEY with Proc-Type: 4,ENCRYPTED and DEK-Info: DES-EDE3-CBC.
I am not sure what is going on, because HTTPS works fine on our development servers.
Is the problem in HapiJS?
Is the problem with the certificate or key themselves?
Is there an Node option I need to be passing in when creating the service?
Please help.
The specified error 06065064:digital envelope routines:EVP_Decryptfinal_ex:bad decrypt occurs in an SSL/TLS connection using OpenSSL (which is what nodejs modules like tls and https actually use) when the privatekey is encrypted (with a passphrase) and the correct passphrase is not provided to decrypt it. The described file format, beginning with a line -----BEGIN RSA PRIVATE KEY----- followed by lines Proc-Type: and DEK-Info: is indeed one of the encrypted formats used by OpenSSL. Specifically this is the encrypted 'traditional' or 'legacy' format; the PKSC8 format added about 2000 but still considered new(!) uses -----BEGIN ENCRYPTED PRIVATE KEY----- and no 822-style headers, only base64 (of the encrypted structure defined by PKCS8); see ursinely-verbose https://security.stackexchange.com/questions/39279/stronger-encryption-for-ssh-keys/#52564 about OpenSSH's use of OpenSSL, which is basically the same as nodejs's use.
The tls module and others that build on it including https ultimately read the key(s) and cert(s) using tls.createSecureContext which accepts in options a member passphrase, or if you need to use multiple keys (and certs) you can provide a passphrase for each key as described in the linked doc.
Alternatively you can avoid the need for a passphrase by converting the key to an unencrypted file, if acceptable under applicable security policies and regulations. (Good policies may prohibit this, but they usually also prohibit getting the privatekey from or providing it to any other system, especially one 'online' somewhere, and your customer is doing the latter.) To retain traditional format do
openssl rsa -in oldfile -out newfile
# and give the passphrase when prompted, or see the man page about -passin
or you can use the 'new' PKCS8 format with
openssl pkey -in oldfile -out newfile
# technically only in release 1.0.0 up, but pretty much everyone is there now
#
# or in all versions back to about 2000
openssl pkcs8 -topk8 -nocrypt -in oldfile -out newfile
For me this error occured after pulling some old code that was workign to a fresh system, I was using too current of a node Version, I downgraded from 17 to 16 and that solved my problem.
Tried checking the github issues related to the TLS, handshake and versions. But couldn't find any.
The final fix was the one suggested by #Greggory Wiley.
Installed nvm - downgraded the node and npm versions. Recomplied the code. And it worked.
In my case I was exporting a certificate from windows to linux inside a docker using openSSL and facing this error.
The problem was in the versions of OpenSLL, when I was converting .pfx file to .crt and .key I was using 3.0.x version on windows, and on linux I had 1.1.1 installed. After I did the same using the same version of OpenSLL on windows it worked.
I had the same issue, I would say that the accepted answer is good expect it does not provide an example where the passphrase is used.
Here's code that worked in my case for express.js
const server = https
.createServer(
{
key: fs.readFileSync("./root/ca/cakey.pem"),
cert: fs.readFileSync("./root/ca/cacert.pem"),
passphrase: "abcdefg",
},
app
)
.listen(PORT, () => {
console.log(`Secure server listening on port:${PORT}`);
});

Storing encrypted PrivateKey's to Java Keystores

Java Keystores (e.g. JKS, PKCS) allow saving private keys (interface
Key) and
certificate chains. However a RSA KeyPair's private key which is encrypted
(e.g. EncryptedPrivateKeyInfo in bouncycastle or in javax) does not implement
Key interface.
What is the correct way to store encrypted private keys in a keystore?
If you already have an EncryptedPrivateKeyInfo, you should be able to use that directly when creating the keystore entry. Java stores the PrivateKey in the KeyStore as EncryptedPrivateKeyInfo format.
You need to use this method in the KeyStore.setKeyEntry(String alias, byte[] key, Certificate[] chain). Documentation here.
The other setKeyEntry method takes in an addtional argument, which is the password, which the Java will construct the EncryptedPrivateKeyInfo itself with the password provided.
Note: Only if the Key Protection Algorithm is supported by Java, it will import the private key, or else it will complain. If it does complain, you can look at other option of decrypting the encrypted private key yourself, and using the other setKeyEntry() method.

Public encryption in crypto on node 0.12

I need to encrypt (and decrypt) a string with a public key previously generated in nodejs (i'm using version 0.12) with crypto module, but i'm unable to do it.
For first i generated the keys in this way:
var diffHell = crypto.createDiffieHellman(60);
diffHell.generateKeys('base64');
var publicKey = diffHell.getPublicKey('base64'); //or whatever 'hex','binary'
var privateKey = diffHell.getPrivateKey('base64'); //or whatever 'hex','binary'
Then i tried to encrypt a string using the generated public key:
crypto.publicEncrypt({key: publicKey}, new Buffer(textToEncrypt));
Running this snippet, node throw this error:
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
at Error (native)
at Object.exports.publicEncrypt (crypto.js:362:18)
[...]
Reading it, I understand that the key must be in PEM format, but i can't find in the documentation how to tranform a public key in PEM.
So, How i can do that? Someone has done this yet?
Diffie-Hellman (Key Exchange) is an algorithm and protocol to derive a shared secret based on modular arithmetic. It is not a public-key cipher in the same way as RSA is. You cannot use Diffie-Hellman for crypto.publicEncrypt().
Node.js' Crypto module doesn't provide a way to generate a public-private RSA key pair, so you either need to use OpenSSL through child_process or use one of the many modules which provide this sort of thing (e.g. ursa).
You do not need to uses ursa for key generation. Instead you can generate keys with openssl then store the generated PEM keys on your server and try to load them in your script

Hex encode ECDSA keys in node.js

I'm building a nodejs app that talks to an API server. The API server requires that each request I make to it includes a X-Signature header using the prime256v1 ECDSA curve and sha256 hash on a particular set of data.
I looked through the crypto and tls documentation but didn't find anything suitable. I have successfully generated a private key with openssl ecparam -name prime256v1 -genkey but it is in PEM format. I have also generated a DER format key. Both of these include some extra metadata like the curve used and in the case of PEM, comments.
I can use these keys for signing operations on my side, but the server requires that I upload a public key using hex encoding (so the server can verify the signatures I make on my requests.)
Specifically the server wants something like the output of the following Python code:
from ecdsa import SigningKey
from binascii import hexlify
hexlify(SigningKey.from_pem(content).to_string())
Sample output for a pubkey (no newlines): c5bd76cd0cd948de17a31261567d219576e992d9066fe1a6bca97496dec634e2c8e06f8949773b300b9f73fabbbc7710d5d6691e96bcf3c9145e15daf6fe07b9
I would prefer not adding python as a dependency to my node app... anyone know of a way I can extract the binary data representing my private key from the PEM or DER files, so I can put it in a buffer and call buffer.toString('hex')? Or a way I can use the native crypto library to generate the ECDSA keypair? Or a library that would do the same?
openssl itself can print out the guts of things, in hex.
Doe the key change? sounds like you can just decode into hex one time, and use that? No need for dependencies - just paste the hex into your node source?

Openssl decryption using a public key

I need to decrypt a file which is encrypted using a private key. I have a public key which I can use to decrypt this file. How can I do this. I did:
openssl rsautl -in file -inkey key.pem
But this is not working. This shows the error as:
unable to load Private Key
3074128072:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:696:Expecting: ANY PRIVATE KEY
Public keys cannot be used to decrypt, they can only be used to encrypt and to verify the encryption signature.
Contrary to everyone, you can in fact decrypt using a Public Key, only however, if your data was encrypted with the appropriate Private Key.
As to how you go about decrypting it, from what I can see the openssl utility doesn't ship with this functionality. It seems you would have to use something that utilises the OpenSSL C API (https://www.openssl.org/docs/man1.0.2/crypto/RSA_public_decrypt.html).
Either use the C API directly or something like PHP's bindings to OpenSSL.
Openssl CLI can achieve "decrypting with the public key" via the rsautl subcommand like so:
openssl rsautl -verify -inkey public_key.pem -pubin -in data.sig -raw -hexdump
Note: here, "decrypt" is loosly defined as modular exponentiation, and the API used is actually the -verify algorithm. Warning that rolling your own crypto is not advised, and misusing RSA is easy to do to create a broken security system.

Resources