[openssl-users] can I parse PKCS8 file and decrypt it later?

Dave Thompson dthompson at prinpay.com
Tue Dec 30 22:48:08 UTC 2014


> From: openssl-users On Behalf Of Bear Giles
> Sent: Tuesday, December 30, 2014 16:53

> I've been able to read and write most objects using both the PEM bio 
> and i2d/d2i functions. I know I can write an encrypted PKCS8 file with 
> PEM_write_bio_PKCS8PrivateKey().
> How do I read encrypted PKCS8 files? I can read unencrypted files with 
> PKCS8_PRIV_KEY_INFO but have been stumped by the encrypted file. 
> 
For PKCS8 encrypted DER: d2i_PKCS8PrivateKey following the usual pattern.

All of the PEM_read_*PrivateKey routines can read *any* privatekey 
as long as the key type is "satisfactory" (and if encrypted the correct 
password is supplied, of course). Thus 
- PEM_read_RSAPrivateKey can read traditional-RSA or PKCS8-RSA 
- PEM_read_DSAPrivateKey can read traditional-DSA or PKCS8-DSA 
- PEM_read_ECPrivateKey can read traditional-EC or PKCS8-EC 
and the slightly less obvious one
- PEM_read_PrivateKey can read any traditional or any PKCS8

On the _write side you have to specify what file format you want, 
but on the _read side the BEGIN line says what file format it is
and you only need to specify what *key* you want from it.

> Obviously 'openssl pkcs8 ...' can do it but maybe I'm overlooking 
> a source of documentation. Otherwise it's a dive into the source code.

> Second question - can I parse encrypted PKCS8 files without decrypting it? 
> I know the traditional keys have to be decrypted (and thus parameter-less 
> readers can't use encrypted files) but I thought PKCS8 was a container and 
> it was possible to parse the object without the password. Does this involve X509_SIG?  
> I noticed that the i2d/d2i PKCS8 functions work with X509_SIG objects.

Using X509_SIG is kind of a crock; it is because "outer" (encrypted) PKCS8
is just AlgorithmIdentifier plus opaque encrypted data while an X.509 signature 
is just AlgorithmIdentifier plus opaque signature data, and this saved one struct!

Yes you can read in a PKCS8-encrypted file with PEM_read_PKCS8 or d2i_PKCS8 
without decrypting, and that's actually the first step of what _read_*PrivateKey 
or d2i_PKCS8PrivateKey does, but what good does that do you? There is SOME key, 
but you can't use it for anything. You don't even know its algorithm or size or 
anything that might be of use in deciding whether or when to use it.

If you just want to read the file because it might become inaccessible,
read the file into memory as-is and then PEM_read_bio_x or d2i_x_bio 
from a memory BIO that reads that memory.




More information about the openssl-users mailing list