RSA keys

RSA keys are asymmetric keys and consists of public and private key both combined forming a key pair.

The namespace DidiSoft.OpeSsl.Rsa contains PublicKey and PrivateKey sub classes that represent RSA keys:

 Namespace DidiSoft.OpenSsl
 +---------+      +---------+    +----------+
 | KeyPair |      |PublicKey|    |PrivateKey|
 ++--------+      +-------+-+    +-----+----+
  ^                       ^            ^
  | DidiSoft.OpenSsl.Rsa  |            |
+-+---------+     +-------+----+ +-----+-------+
|RsaKeyPair |     |RsaPublicKey| |RsaPrivateKey|
+-----------+     +------------+ +-------------+

Table of contents

Create RSA keys

RSA keys are created as a key pair. Then from the key pair the public and private key can be taken and used for a cryptographic operation or saved to a file or otherĀ  storage.

The most easy way to create an RSA key pair is with the method GenerateKeyPair provided in DidiSoft.OpenSsl.RsaKeyPair:

1
2
3
DidiSoft.OpenSsl.Rsa.RsaKeyPair kp = DidiSoft.OpenSsl.Rsa.RsaKeyPair.GenerateKeyPair(KeyLength.Length2048);
RsaPublicKey pubKey = kp.GetPublicKey();
RsaPrivateKey privKey = kp.GetPrivateKey();

Load RSA keys

An RSA public key can be loaded from a file or byte array with the static Load method:

1
DidiSoft.OpenSsl.Rsa.RsaPublicKey pubKey = DidiSoft.OpenSsl.Rsa.RsaPublicKey.Load("akey.pem");

A private RSA key can be loaded from an unprotected source or from a password protected storage (encrypted private key)

1
2
DidiSoft.OpenSsl.Rsa.RsaPrivateKey privKey = DidiSoft.OpenSsl.Rsa.RsaPrivateKey.Load("seckey.pem");
DidiSoft.OpenSsl.Rsa.RsaPrivateKey priv2Key = DidiSoft.OpenSsl.Rsa.RsaPrivateKey.Load("protected.key", "key password");

Save RSA keys

The public and private keys can be stored in PEM or DER format specified a last parameter of the Save method:

1
2
3
4
5
6
7
8
9
using DidiSoft.OpenSsl.Rsa;
...
RsaKeyPair kp = RsaKeyPair.GenerateRsaKeyPair(KeyLength.Length2048);
RsaPublicKey pubKey = kp.GetPublicKey();
RsaPrivateKey privKey = kp.GetPrivateKey();
 
bool pemFormat = true;
pubKey.Save(@"Data\public_key.pem", pemFormat);
privKey.Save(@"Data\private_key.pem", pemFormat);

Base-64 encoded format

Some applications use RSA keys in base-64 encoded format. For such cases the keys can be exported with the ToBase64String method.

Obtain public key from private key

A public RSA key can be restored from the private key with the following code block:

1
2
RsaPrivateKey privKey = ...
RsaPublicKey pubKey = (RsaPublicKey)privKey.GetPublicKey();

Key usage

RSA keys can be used for cryptography operations with the OpenSslRsa class.
X.509 Certificates
CMS/PKCS7 cryptography operations
S/MIME cryptography operations