Delete key from a pgp KeyStore with C# and VB.NET

This article demonstrates how to delete keys from a KeyStore.

We can delete only the public key, only the private key or both of them (a key pair) at once.

The methods used are:

KeyStore.DeleteKeyPair – deletes a key pair,
KeyStore.DeletePublicKey – deletes a public key only
KeyStore.DeletePrivateKey – deletes a public key only

All of these methods return true if the delete operation is successful, false if there is no such key.

The key to be deleted can be addressed either by its Key ID or with part or complete User ID. The example code below illustrates all of the delete key methods:

C# example

using System;
using DidiSoft.Pgp;
 
public class DeleteKeyPair
{
 public static void Demo()
 {
   // initialize the key store
   KeyStore ks = new KeyStore(@"DataFiles\key.store", "changeit");
 
   // deletes the first key pair with this user Id
   bool success = ks.DeleteKeyPair("demo2@support.com");
   // only public key
   success = ks.DeletePublicKey("0A42BC7823");
   // only private key
   success = ks.DeletePrivateKey("Demo <demo@didisoft.com>");
 }
}

VB.NET code

Imports System
Imports DidiSoft.Pgp
 
Public Class DeleteKeyPair
 Public Shared Sub Demo()
  ' initialize the key store
  Dim ks As New KeyStore("DataFiles\key.store", "changeit")
 
  ' delete the first key pair with this user Id
  Dim success As Boolean = ks.DeleteKeyPair("demo2@didisoft.com")
   ' only public key
   success = ks.DeletePublicKey("0A42BC7823")
   ' only private key
   success = ks.DeletePrivateKey("Demo <demo@didisoft.com>")
 End Sub
End Class

If there is more than one key with the same user Id then we can use the overloaded version of the DeleteKeyPair method that accepts Key Id of type Int32.

Summary 

This chapter illustrated how to remove keys from a KeyStore.