Decrypting OpenPGP data in Android

This sample shows how to decrypt an OpenPGP encrypted file in Android.

The encrypted file and the private key that will be used for decryption are located in the Assets folder of the application.

The decrypted data file is stored in the private context path

package android.demo;
 
import java.io.*;
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 DecryptStreamDemo extends Activity {
 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TextView tv = new TextView(this);
 
    InputStream encryptedStream = null;
    InputStream keyStream = null;
    OutputStream decryptedStream = null;     				
 
    try {
        // load data and private key stream
        encryptedStream = this.openFileInput("OUTPUT.pgp");
 
        AssetManager assets = getAssets();
        keyStream = assets.open("private_key.asc");
        String private_key_password = "my password";
 
	// specify the output stream
	decryptedStream = this.openFileOutput("OUTPUT.txt", MODE_PRIVATE);
 
	tv.append("Decrypting ...");
	String originalFileName = pgp.decryptStream(encryptedStream,
						keyStream,
						private_key_password,
						decryptedStream);
 
	tv.append("Decryption done. Original data file name was " + originalFileName);
	tv.append("\n\n");
	tv.append("Decrypted in " + this.getFileStreamPath("OUTPUT.txt").getAbsolutePath())
    } catch (Exception e) {
 	tv.append(e.getMessage());
    } finally {
	// cleanup
	if (encryptedStream != null)
 	  encryptedStream.close();
	if (keyStream != null)
	  keyStream.close();
	if (decryptedStream != null)
	  decryptedStream.close();
    }
 
    setContentView(tv);
 }
}

A working example can be found in /Examples folder in the library distribution ZIP archive.