Importing .pgp keys in Java

Existing OpenPGP keys obtained from other sources can be used directly or imported in a KeyStore object for later use or modifications.

We can import:

  • standalone pgp keys (.asc files) by using
  • whole key rings, for example directly load the keys of an existing PGP or GnuPG installation pubring.pkr and secring.skr files
  • keys from another KeyStore instance

Methods used:

  • KeyStore.importPublicKey – imports only public keys
  • KeyStore.importPrivateKey – imports only private keys
  • KeyStore.importKeyRing – imports all keys
  • KeyStore.importKeyStore – imports keys from another KeyStore

Example code

This example demonstrates how to import existing keys from a standalone files into a KeyStore object.

import com.didisoft.pgp.*;
public class ImportKeysDemo {
 public static void main(String[] args) {
  // initialize the KeyStore. The key store file may not exist
  // and subsequent operations will create it
  KeyStore keyStore = new KeyStore("my.keystore", "keystore password");
  try {
    // import private key
    KeyPairInformation key = keyStore.importKey("private.asc");
    // import public key
    KeyPairInformation key2 = keyStore.importKey("public.asc");
    // imports key ring file. The file may contain public, private or 
    // both type of keys if it is in ASCII armored format
    KeyPairInformation[] manyKeys = keyStore.importKeyRing("keypair.asc");	
  } catch (PGPException e) {
    System.out.println("Error reading key files : " + e.getMessage());
  } catch (IOException e) {

After the key has been imported it can be inspected or edited.