Decrypting and verifying pgp data programatically in Android (OBSOLETE)

In this chapter we are going to show how to decrypt and verify a previously one pass signed and encrypted OpenPGP data with the help of DidiSoft OpenPGP Library for Android.

Example code

The complete example is available in the /Examples/src/android/DecryptAndVerifyDemo.java file in the library distribution archive.

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import com.didisoft.pgp.PGPException;
import com.didisoft.pgp.PGPLib;
 
public class DecryptAndVerifyDemo extends Activity {
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   TextView tv = new TextView(this);
 
   boolean signatureVerified = this.decryptAndVerify();
   if (signatureVerified) {                
	tv.append("Signature has been verified!");
   } else {
        tv.append("Signature is wrong!");
   }
   setContentView(tv);
 }
 
 public boolean decryptAndVerify() throws IOException, PGPException {	
  // create an instance of the library
  PGPLib pgp = new PGPLib();
 
  InputStream signedStream = null;
  InputStream privateDecryptionKeyStream = null;
  InputStream publicVerificationKeyStream = null;
  OutputStream decryptedStream = null;
 
  boolean signatureVerified = false; 
  try {
   // load data and public key stream
   signedStream = this.openFileInput("OUTPUT.pgp");
 
   AssetManager assets = getAssets();
   privateDecryptionKeyStream = assets.open(key2_private);
   String privateDecryptionKeyPassword = key2_private_password; 
 
   publicVerificationKeyStream = assets.open(public_key);
 
   // specify output stream
   decryptedStream = this.openFileOutput("OUTPUT.txt", MODE_PRIVATE);            
   signatureVerified = pgp.decryptAndVerifyStream(signedStream, 
						 privateDecryptionKeyStream,
				                 privateDecryptionKeyPassword,
						 publicVerificationKeyStream,
						 decryptedStream);
 
   return signatureVerified;
  } finally {
   // cleanup
   if (signedStream != null) 
	signedStream.close();
   if (privateDecryptionKeyStream != null) 
	privateDecryptionKeyStream.close();
   if (publicVerificationKeyStream != null) 
	publicVerificationKeyStream.close();
   if (decryptedStream != null) 
	decryptedStream.close();
 }    
}

The decryptAndVerify method is design to process also encrypted only data, signed only data and clear text signed as well.

Summary

This article has introduced the API method used to decrypt and verify OpenPGP data in one step.

List of methods used: