Import keys in a pgp KeyStore with C# and VB.NET

The example below demonstrates how to import an existing OpenPGP public key, private key and a key pair (both keys) in a KeyStore object

C# example

using System;
using DidiSoft.Pgp;
 
public class ImportKeys
{
   public static void Demo()
   {
      // initialize the key store
      KeyStore keyStore = new KeyStore("pgp.keystore", "changeit");       
 
      KeyPairInformation key1 = keyStore.ImportPublicKey("public_key.asc");
 
      KeyPairInformation key2 = keyStore.ImportPrivateKey("private_key.asc");   
      // if private_key.asc is the private key of public_key.asc then key2 will 
      // contain the data of key1 as well
 
      KeyPairInformation[] manyKeys = keyStore.ImportKeyRing("pubring.pkr");
    }
}

VB.NET code

Imports System
Imports DidiSoft.Pgp
 
Public Class ImportKeys
 Public Shared Sub Demo()
   ' initialize the key store
   Dim keyStore As New KeyStore("pgp.keystore", "changeit")
 
   Dim key1 As KeyPairInformation = keyStore.ImportPublicKey("public_key.asc")
 
   Dim key2 As KeyPairInformation = keyStore.ImportPrivateKey("private_key.asc")
   ' if private_key.asc is the private key of public_key.asc then key2 will 
   ' contain the data of key1 as well
 
   Dim manyKeys As KeyPairInformation() = keyStore.ImportKeyRing("pubring.pkr")
 End Sub
End Class

Note that with the ImportKeyRing method we can import a private key file without specifying the private key password, but anyway in order to use it we should pass its password when invoking decryption and signing methods.

Reusing existing key rings from GnuPG, Symantec PGP

We can reuse existing key rings from GnuPG and Symantec PGP transparently by importing them in a KeyStore object.

For example if we wish to use those existing keys in a read only manner, we have to:

1. create an in-memory located KeyStore object

2. invoke KeyStore.ImportKeyRing to import the public key ring (pubring.pkr for Symantec PGP and pubring.gpg for GnuPG) and the secret key ring (secring.skr for Symantec PGP and secring.gpg for GnuPG)

Afterwards we can refer to the keys the same way we do from the command line, either by hexadecimal Key Id or by User Id. Check here for an example.

Summary

In this chapter we have illustrated how to import OpenPGP keys and whole key rings into a KeyStore object.

You can also check how to export keys from a KeyStore and how to import X.509 keys wrapped transparently as OpenPGP keys.