This chapter describes how to export a key from a KeyStore instance in OpenPGP Library for Android.
The example code below assumes that either a key was previously imported in the same KeyStore or was generated there and the KeyStore was saved to a file “my.keystore”.
Example code
import java.io.*; import android.content.*; import android.os.Bundle; import android.widget.TextView; import com.didisoft.pgp.*; import com.didisoft.pgp.storage.*; public class KeyStoreExportKeyDemo extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); try { this.exportKey(this, tv); } catch (Exception e) { tv.append(Html.fromHtml(e.getMessage())); } tv.setMovementMethod(new ScrollingMovementMethod()); setContentView(tv); } // Exports the first key contained in the KeyStore public void exportKey(Context ctx, TextView tv) throws IOException, PGPException { KeyStore keyStore = new KeyStore(new AndroidContextFileKeyStorage(ctx, "my.keystore")); OutputStream keyPairStream = null; OutputStream publicKeyStream = null; OutputStream privateKeyStream = null; try { KeyPairInformation[] keys = keyStore.getKeys(); String userId = keys[0].getUserIDs()[0]; // specifies will the output be ASCII armored or binary boolean asciiArmor = true; // export public and private key into a single file keyPairStream = ctx.openFileOutput("keypair.asc", MODE_PRIVATE); keyStore.exportKeyRing(keyPairStream, userId, asciiArmor); tv.append("Key pair exported to :"); tv.append(ctx.getFileStreamPath("keypair.asc").getAbsolutePath()); tv.append("\n"); // export only public key publicKeyStream = ctx.openFileOutput("pubkey.asc", MODE_PRIVATE); keyStore.exportPublicKey(publicKeyStream, userId, asciiArmor); tv.append("Public key exported to :"); tv.append(ctx.getFileStreamPath("pubkey.asc").getAbsolutePath()); tv.append("\n"); // export only private key privateKeyStream = ctx.openFileOutput("privkey.asc", MODE_PRIVATE); keyStore.exportPublicKey(privateKeyStream, userId, asciiArmor); tv.append("Private key exported to :"); tv.append(ctx.getFileStreamPath("privkey.asc").getAbsolutePath()); tv.append("\n"); } finally { if (keyPairStream != null) keyPairStream.close(); if (publicKeyStream != null) publicKeyStream.close(); if (privateKeyStream != null) privateKeyStream.close(); } } } |
The complete example is available in the /Examples/src/android/KeyStoreExportKeyDemo.java file located in the library distribution archive.
Summary
This chapter illustrated how to export a key pair from a com.didisoft.pgp.KeyStore instance.
List of methods used:
KeyStore.loadFromStream | initializes the contents of a KeyStore object from a Stream |
KeyStore.exportKeyRing | exports the public and private key components of a key pair in one place |
KeyStore.exportPublicKey | exports only the public key component of a key pair |
KeyStore.exportPrivateKey | exports only the private key component of a key pair |