How to Read .Pem File to Get Private and Public Key

How to save public key from a certificate in .pem format

There are a couple ways to do this.

First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:

E:\> openssl x509 -pubkey -noout -in cert.pem  > pubkey.pem

If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.

openssl> x509 -pubkey -noout -in cert.pem

Output will look something like this:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-----

How do I get the public key of a pem file?

Copy the public key to clipboard.

Linux

ssh-keygen -f private.pem -y | xclip

MacOS

ssh-keygen -f private.pem -y | pbcopy

Save to file

ssh-keygen -f private.pem -y > public.pub

Note that if your permissions are vague on the .pem file, then ssh-keygen will generate an empty .pub file.

You can usually fix this with:

chmod 400 private.pem 

[OpenSSL} Read certificate.pem to get the public key in RSA format in C lang

You want PEM_read_X509():

 X509 *PEM_read_X509(FILE *fp, X509 **x, pem_password_cb *cb, void *u);
.
.
.

The PEM read functions all take an argument TYPE **x and return a TYPE * pointer. Where TYPE is whatever structure the function uses. If x is NULL then the parameter is ignored. If x is not NULL but *x is NULL then the structure returned will be written to *x. If neither x nor *x is NULL then an attempt is made to reuse the structure at *x (but see BUGS and EXAMPLES sections). Irrespective of the value of x a pointer to the structure is always returned (or NULL if an error occurred).

The PEM functions which write private keys take an enc parameter which specifies the encryption algorithm to use, encryption is done at the PEM level. If this parameter is set to NULL then the private key is written in unencrypted form.

The cb argument is the callback to use when querying for the pass phrase used for encrypted PEM structures (normally only private keys).

For the PEM write routines if the kstr parameter is not NULL then klen bytes at kstr are used as the passphrase and cb is ignored.

If the cb parameters is set to NULL and the u parameter is not NULL then the u parameter is interpreted as a null terminated string to use as the passphrase. If both cb and u are NULL then the default callback routine is used which will typically prompt for the passphrase on the current terminal with echoing turned off.

You'll likely only need something like this:

FILE *pemFile = fopen(...);
X509 *x509 = PEM_read_X509( pemFile, NULL, NULL, NULL );

Once you have the X509 certificate, you can use X509_get_pubkey() to get the RSA public key:

#include <openssl/x509.h>

EVP_PKEY *X509_get_pubkey(X509 *x);
EVP_PKEY *X509_get0_pubkey(const X509 *x);

Does .pem file contain both private and public keys?

A PEM file may contain just about anything including a public key, a private key, or both, because a PEM file is not a standard. In effect PEM just means the file contains a base64-encoded bit of data. It is called a PEM file by allusion to the old Privacy-Enhanced Mail standards which preceded S/MIME as a mail security standard. These standards specified the format of various keys and messages in a particular base64 format. See RFC 1421 for example.

Typically a PEM file contains a base64 encoded key or certificate with header and footer lines of the form -----BEGIN <whatever>----- and -----END <whatever>----. Over time there have evolved many possibilities for <whatever>, including private keys, public keys, X509 certificates, PKCS7 data, files containing multiple certificates, files containing both the private key and the X509 certificate, PKCS#10 certificate signing requests, ...

RFC 7468 has been written to document this de facto format.

How to read a PEM RSA private key from .NET

Update 03/03/2021

.NET 5 now supports this out of the box.

To try the code snippet below, generate a keypair and encrypt some text at http://travistidwell.com/jsencrypt/demo/

var privateKey = @"-----BEGIN RSA PRIVATE KEY-----
{ the full PEM private key }
-----END RSA PRIVATE KEY-----";

var rsa = RSA.Create();
rsa.ImportFromPem(privateKey.ToCharArray());

var decryptedBytes = rsa.Decrypt(
Convert.FromBase64String("{ base64-encoded encrypted string }"),
RSAEncryptionPadding.Pkcs1
);

// this will print the original unencrypted string
Console.WriteLine(Encoding.UTF8.GetString(decryptedBytes));

Original answer

I solved, thanks. In case anyone's interested, bouncycastle did the trick, just took me some time due to lack of knowledge from on my side and documentation. This is the code:

var bytesToDecrypt = Convert.FromBase64String("la0Cz.....D43g=="); // string to decrypt, base64 encoded

AsymmetricCipherKeyPair keyPair;

using (var reader = File.OpenText(@"c:\myprivatekey.pem")) // file containing RSA PKCS1 private key
keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject();

var decryptEngine = new Pkcs1Encoding(new RsaEngine());
decryptEngine.Init(false, keyPair.Private);

var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));

How to store private and public key into pem file generated by rsa module of python

The Github site of Python RSA refers via its homepage to this documentation, according to which the library has dedicated methods to export the keys in PKCS#1 format (methods rsa. PublicKey#save_pkcs1() or rsa.PrivateKey#save_pkcs1()) or to import them (classmethods rsa.PublicKey.load_pkcs1() or rsa.PrivateKey.load_pkcs1()). As encodings PEM (text) or DER (binary) is supported, e.g.:

import rsa

# Use at least 2048 bit keys nowadays, see e.g. https://www.keylength.com/en/4/
publicKey, privateKey = rsa.newkeys(2048)

# Export public key in PKCS#1 format, PEM encoded
publicKeyPkcs1PEM = publicKey.save_pkcs1().decode('utf8')
print(publicKeyPkcs1PEM)
# Export private key in PKCS#1 format, PEM encoded
privateKeyPkcs1PEM = privateKey.save_pkcs1().decode('utf8')
print(privateKeyPkcs1PEM)

# Save and load the PEM encoded keys as you like

# Import public key in PKCS#1 format, PEM encoded
publicKeyReloaded = rsa.PublicKey.load_pkcs1(publicKeyPkcs1PEM.encode('utf8'))
# Import private key in PKCS#1 format, PEM encoded
privateKeyReloaded = rsa.PrivateKey.load_pkcs1(privateKeyPkcs1PEM.encode('utf8'))

plaintext = "vinay kumar shukla".encode('utf8')
print("Plaintext: ", plaintext)

ciphertext = rsa.encrypt(plaintext, publicKeyReloaded)
print("Ciphertext: ", ciphertext)

decryptedMessage = rsa.decrypt(ciphertext, privateKeyReloaded)
print("Decrypted message: ", decryptedMessage)


Related Topics



Leave a reply



Submit