The format of the base64 contents inside:
-----BEGIN RSA PRIVATE KEY-----
...base64 encoded DER ASN.1 RSAPrivateKey...
-----END RSA PRIVATE KEY-----
is documented in RFC3447 - Appendix A.1.2 - RSA private key syntax:
RSAPrivateKey ::= SEQUENCE {
version Version,
modulus INTEGER, -- n
publicExponent INTEGER, -- e
privateExponent INTEGER, -- d
prime1 INTEGER, -- p
prime2 INTEGER, -- q
exponent1 INTEGER, -- d mod (p-1)
exponent2 INTEGER, -- d mod (q-1)
coefficient INTEGER, -- (inverse of q) mod p
otherPrimeInfos OtherPrimeInfos OPTIONAL
}
You already know how to encode that using the DER flavor of ASN.1; and the question is about how to actually write that DER binary data to a file.
That next step is documented in RFC 1421 - 4.3.2.4 Step 4: Printable Encoding
- they document encoding the binary data in base64
- encoding the output as lines of text
- with each line (except the last) containing exactly 64 printable characters
- and the final line containing 64 or fewer printable characters
There is then the "Encapsulation Boundary" (EB), used to delimit encapsulated PEM messages.
- the pre-EB string is:
-----BEGIN PRIVACY-ENHANCED MESSAGE-----
- the post-EB string is:
-----END PRIVACY-ENHANCED MESSAGE-----
It was the defuct Privacy Enhanced Mail that used:
- five hyphens (
-----
)
BEGIN
something
- five hyphens (
-----
)
followed by
- five hyphens (
-----
)
END
something
- five hyphens (
-----
)
Those PEM conventions were carried over for public key, private key, and certificates, but with suitable changed wording:
-----BEGIN RSA PUBLIC KEY-----
...base64 encoded DER ASN.1 RSAPublicKey...
-----END RSA PUBLIC KEY-----
-----BEGIN RSA PRIVATE KEY-----
...base64 encoded DER ASN.1 RSAPrivateKey...
-----END RSA PRIVATE KEY-----
-----BEGIN PUBLIC KEY-----
...base64 encoded DER ASN.1 SubjectPublicKeyInfo...
-----END PUBLIC KEY-----
-----BEGIN PRIVATE KEY-----
...base64 encoded DER ASN.1 PrivateKeyInfo...
-----END PUBLIC KEY-----
-----BEGIN CERTIFICATE-----
...base64 encoded DER ASNl.1 Certificate...
-----END CERTIFICATE-----