Change the password of a pgp key with C# and VB.NET

This example demonstrates how to change the password of an OpenPGP private key located in a KeyStore object.

If we have a standalone OpenPGP private key file and want to change it’s password we can use the PGPKeyPair class that provides similar functionality, or we can import it in a KeyStore, execute the example code below and export it back to a file.

C# sample

using System;
using DidiSoft.Pgp;
 
class ChangeKeyPassword
{
 public void Demo()
 {
  // initialize the key store
  KeyStore ks = new KeyStore(@"DataFiles\key.store", "changeit");
 
  string privateKeyUserId = "support@didisoft.com";
  string currentPassword = "changeit";
  string newPassword = "new pass phrase";
 
  // change password
  bool keyFound = false;
  try 
  {
    keyFound = ks.ChangePrivateKeyPassword(privateKeyUserId,
						currentPassword,
						newPassword);
  } catch (DidiSoft.Pgp.Exceptions.WrongPasswordException e) 
  {
    Console.WriteLine("The current password is wrong.");
  }
 
  if (keyFound)
  {
	Console.WriteLine("Password successfully changed.");
  }
  else
  {
	Console.WriteLine("No secret key was found with user Id = " + privateKeyUserId);
  }
 }
}

VB.NET code sample

Imports System
Imports DidiSoft.Pgp
 
Class ChangeKeyPassword
 Public Sub Demo()
  ' initialize the key store
  Dim ks As New KeyStore("DataFiles\key.store", "changeit")
 
  Dim privateKeyUserId As String = "support@didisoft.com"
  Dim currentPassword As String = "changeit"
  Dim newPassword As String = "new pass phrase"
 
  ' change password
  Dim keyFound As Boolean = False
  Try 
    keyFound = _
        ks.ChangePrivateKeyPassword(privateKeyUserId, _
				    currentPassword, _
				    newPassword)
  Catch e As DidiSoft.Pgp.Exceptions.WrongPasswordException 
    Console.WriteLine("The current password is wrong.")
  End Try
 
  If keyFound Then
	Console.WriteLine("Password successfully changed.")
  Else
	Console.WriteLine("No secret key was found with user Id = " + privateKeyUserId)
  End If
 End Sub
End Class

Summary

This chapter illustrated how to change the password of an OpenPGP private key.

The PGPKeyPair class also provides similar method for changing the password of an OpenPGP private key located in a file on the disk.