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\", "changeit");
  string privateKeyUserId = "";
  string currentPassword = "changeit";
  string newPassword = "new pass phrase";
  // change password
  bool keyFound = false;
    keyFound = ks.ChangePrivateKeyPassword(privateKeyUserId,
  } catch (DidiSoft.Pgp.Exceptions.WrongPasswordException e) 
    Console.WriteLine("The current password is wrong.");
  if (keyFound)
	Console.WriteLine("Password successfully changed.");
	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\", "changeit")
  Dim privateKeyUserId As String = ""
  Dim currentPassword As String = "changeit"
  Dim newPassword As String = "new pass phrase"
  ' change password
  Dim keyFound As Boolean = False
    keyFound = _
        ks.ChangePrivateKeyPassword(privateKeyUserId, _
				    currentPassword, _
  Catch e As DidiSoft.Pgp.Exceptions.WrongPasswordException 
    Console.WriteLine("The current password is wrong.")
  End Try
  If keyFound Then
	Console.WriteLine("Password successfully changed.")
	Console.WriteLine("No secret key was found with user Id = " + privateKeyUserId)
  End If
 End Sub
End Class


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.