OpenPGP encryption in Android

This example demonstrates how to perform OpenPGP encryption with DidiSoft OpenPGP Library for Android.

The code snippet below assumes that the public key that will be used for encryption and the data file that will be encrypted are located in the assets folder.

The encrypted data is stored in the private context path of the application.

package android.demo;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.widget.TextView;
import com.didisoft.pgp.PGPException;
import com.didisoft.pgp.PGPLib;
public class EncryptStreamDemo extends Activity {
 public void onCreate(Bundle savedInstanceState) {
  TextView tv = new TextView(this);
  InputStream dataStream = null;
  InputStream keyStream = null;
  OutputStream outStream = null;        
  // encrypt
  try {
    PGPLib pgp = new PGPLib();
    AssetManager assets = ctx.getAssets();       
    // load data and public key stream
    dataStream ="INPUT.txt");
    keyStream ="public_key.asc");
    // specify output stream
    outStream = this.openFileOutput("OUTPUT.pgp", MODE_PRIVATE);
    // This is just a file name label that will be associated with the encrypted data
    String internalFileNameLabel = "INPUT.txt";
    // specifies will the output be ASCII armored or binary
    boolean asciiArmor = true;
    // specifies should integrity check information be appended
    boolean withIntegrityCheck = false;
    tv.append("Encrypting ...");
    pgp.encryptStream(dataStream, internalFileNameLabel, keyStream, outStream, asciiArmor, withIntegrityCheck);
    tv.append("Encryption done.");
  } catch (Exception e) {
    tv.append("Exception : " + e.getMessage());
  } finally {
    // cleanup
    if (dataStream != null)
    if (keyStream != null)
    if (outStream != null)

The example above demonstrates how to encrypt a file located in the ‘assets‘ folder of an Android application.

You can also check the example that shows how to perform OpenPGP decryption.