opyeb asn1lab

asn1lab · Keys

PKCS#8, SPKI and PKCS#1: three shapes of key file

PrivateKeyInfo, SubjectPublicKeyInfo, RSAPrivateKey, ECPrivateKey, encrypted PKCS#8

Key files look numerous, but the envelopes are few. A private key is PKCS#8, PKCS#1 or SEC1 ECPrivateKey; a public key is almost always SubjectPublicKeyInfo (SPKI). The PEM label and the first tag tell you which.

PEM labelStructureFirst child
PRIVATE KEYPKCS#8 PrivateKeyInfoINTEGER 0
ENCRYPTED PRIVATE KEYPKCS#8 EncryptedPrivateKeyInfoSEQUENCE (AlgorithmIdentifier)
RSA PRIVATE KEYPKCS#1 RSAPrivateKeyINTEGER 0 then a large INTEGER
EC PRIVATE KEYSEC1 ECPrivateKeyINTEGER 1
PUBLIC KEYSubjectPublicKeyInfoSEQUENCE (AlgorithmIdentifier)

PKCS#8: a private key with its algorithm

PrivateKeyInfo ::= SEQUENCE { version INTEGER, privateKeyAlgorithm AlgorithmIdentifier, privateKey OCTET STRING, attributes [0] OPTIONAL }

The privateKey OCTET STRING contains the actual key one level deeper: PKCS#1 RSAPrivateKey for RSA, ECPrivateKey for EC. Decode a PKCS#8 key and you will see a second SEQUENCE begin inside the OCTET STRING.

SPKI: the standard public key envelope

SubjectPublicKeyInfo ::= SEQUENCE { algorithm AlgorithmIdentifier, subjectPublicKey BIT STRING }

For an RSA public key the BIT STRING holds SEQUENCE { modulus INTEGER, publicExponent INTEGER }. For EC it holds the uncompressed point starting with 0x04 (04 ‖ X ‖ Y). That is why opening the BIT STRING shows a SEQUENCE for RSA and what looks like random bytes for EC.

Encrypted PKCS#8

ENCRYPTED PRIVATE KEY is EncryptedPrivateKeyInfo: SEQUENCE { encryptionAlgorithm AlgorithmIdentifier, encryptedData OCTET STRING }. The algorithm holds PBES2 (1.2.840.113549.1.5.13) with PBKDF2 (1.2.840.113549.1.5.12) parameters, and encryptedData is ciphertext. The inner key structure is unreadable until it is decrypted with the password.

Common confusions

Real private keys should not be pasted into a browser at all. Study structure with the synthetic samples, and handle production keys offline.

Questions

What is the difference between PKCS#8 and PKCS#1?

PKCS#1 is an RSA-only structure; PKCS#8 is a general envelope that names the algorithm. The usual form places PKCS#1 inside PKCS#8, and EC or Ed25519 keys use the same envelope.

Can a private key be derived from a public key?

For RSA the private exponent is mathematically derivable from modulus and public exponent, but not at real key sizes. For EC the private scalar cannot be computed from the public point.

What if the SPKI BIT STRING is empty?

The structure is invalid or truncated. A BIT STRING needs at least the unused-bit count byte plus key bytes.

Load the synthetic PKCS#8 and SPKI samples and compare the two structures side by side.

Open the tool

This guide follows ITU-T X.690 (DER/BER), RFC 5280 (X.509), RFC 5208 (PKCS#8), RFC 5480 (EC public keys), RFC 5915 (EC private keys) and RFC 3279 (ECDSA signatures). Every example is synthetic.