Export keys

Examples ›› Programs ››
Parent Previous Next

This example will demonstrate how to export a key from a KeyStore file. This is an operation that usually follows after we generate a key pair and have to send the public key to our partners so they could encrypt data that only we will be able to read.


import java.io.IOException;

import com.didisoft.pgp.*;

import com.didisoft.pgp.exceptions.*;

public class ExportKeysDemo {

public static void main(String[] args) {

 // initialize the key store                

 KeyStore keyStore = new KeyStore("pgp.keystore", "changeit");

 // should the output be ASCII or binary

 boolean asciiArmor = false;

 // export public key        

 try {        

   keyStore.exportPublicKey("exported_pub.pkr",

                            "demo@didisoft.com",

                            asciiArmor);                

 } catch (NoPublicKeyFoundException e) {

   System.out.println("There is no public key in the KeyStore with " +

                      "the specified User ID");

 } catch (IOException e) {

   System.out.println(e.getMessage());

 }

 // export private key

 try {

   keyStore.exportPrivateKey("exported_sec.skr",

                             "demo@didisoft.com",

                             asciiArmor);                

 } catch (NoPrivateKeyFoundException e) {

   System.out.println("There is no private key in the KeyStore with " +

                      "the specified User ID");

 } catch (IOException e) {

   System.out.println(e.getMessage());

 }

 // export the whole key pair in one file (in this case

 // only ASCII armored output is accepted)

 try {

   keyStore.exportKeyRing("keypair.asc", "demo@didisoft.com");                                

 } catch (NoPublicKeyFoundException e) {

   System.out.println("There is no key pair in the KeyStore with " +

                      "the specified User ID");

 } catch (IOException e) {

   System.out.println(e.getMessage());

 }

}

}