Storing encrypted PrivateKey's to Java Keystores - bouncycastle

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.

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

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

How to decrypt an encrypted RSA key .pem file with 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-----

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?

Jasypt StandardPBEStringEncryptor setting password in spring bean configuration file

When using Jasypt's StandardPBEStringEncryptor we have to set password explicitly in spring bean configuration file. Is it ok and secure to have the password in the bean configuration file? Will it be a problem in PCI Compliance to store the encryptor password?
This will not be PCI compliant. Data encrypting keys cannot be stored in plaintext. The specific point is 3.5.2 which is:
Examine system configuration files to
verify that keys are stored in
encrypted format, and that
key-encrypting keys are stored
separately from data-encrypting keys.
You would probably also have other issues around the key management area, such as 3.6.6 (Split knowledge and dual control of keys)
Verify that key-management procedures
are implemented to require split
knowledge and dual control of keys
(for example, requiring two or three
people, each knowing only their own
part of the key, to reconstruct the
whole key).
Key management is the most challenging part of PCI compliance. You may want to consider using a (already PCI compliant) 3rd party to manage your card data. If you are rolling your own then I would advise that you bring in the assistance of a QSA (PCI Qualified Security Assesor) at the earliest opportunity to evaluate the security you're planning on implementing. ultimately it will be the QSA that you need to convince in order to pass your PCI requirements, and they will be more than happy to advise.
You need to store the symmetric key somewhere. A configuration file is a good place, as long as no one has access to it.
I have an idea
you can encrypt all of your plain password with keyPair of keystore.jks. You know that the keystore.jks has its own password. you can remember that password and when your program get started enter it on console. for example when your program start:
Console console = System.console();
keyPair = loadKeystore(new String(console.readPassword()));
private static KeyPair loadKeystore(String pwd) {
InputStream is = Main.class.getResourceAsStream("/keystore.jks");
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(is, s.toCharArray());
String alias = "youralias";
Key key = keystore.getKey(alias, pwd.toCharArray());
if (key instanceof PrivateKey) {
// Get certificate of public key
Certificate cert = keystore.getCertificate(alias);
// Get public key
PublicKey publicKey = cert.getPublicKey();
// Return a key pair
return new KeyPair(publicKey, (PrivateKey) key);
}
return null;
}
when you return the keypair you can uses it for encrypt your password.
key = loadKeystore("yourpass").getPrivate().getEncoded()
goodluck

Resources