user95437
user95437

Reputation: 69

How to generate a string that is valid PEM private key?

For a PEM private certificate, I assume you need a string like this:

-----BEGIN PRIVATE KEY-----
YzNhYjhmZjEzNzIwZThhZDkwNDdkZDM5NDY2YjNjODk3NGU1OTJjMmZhMzgzZDRhMzk2MDcxNGNhZWYwYzRmMg==
-----END PRIVATE KEY-----

So what I did was:

$privateKey = '-----BEGIN PRIVATE KEY-----';
$privateKey .='\n'.base64_encodehash(('sha256','foobar'));
$privateKey .='\n-----END PRIVATE KEY-----';

But openssl_pkey_get_private($privateKey) returns false and not a valid resource. I assumed PEM is just base64 string. What have I done wrong? (I found this via Google: http://www.cryptosys.net/pki/manpki/pki_pemstring.html)

Upvotes: 2

Views: 3497

Answers (1)

Matt Caswell
Matt Caswell

Reputation: 9457

There are different PEM formats for different types of objects. On the face of it PEM is just base 64 encoded data enclosed within the BEGIN and END markers. PEM files that begin with the "BEGIN PRIVATE KEY" markers contain base64 encoded data that conforms to the PKCS#8 standard. In particular see section 5 of RFC5208 (https://www.rfc-editor.org/rfc/rfc5208). Normally you would not create these files yourself from scratch you would use some sort of library or tool to do it for you (such as OpenSSL).

Upvotes: 2

Related Questions