pgp sign and encrypt in one pass in Android

The OpenPGP signed and encrypted format combines an encrypted packet which contains inside a signed message. This way both the data is protected and also we can be sure that it has been sent by trusted sender.

In this article we will illustrate how to perform OpenPGP sign and encrypt with DidiSoft OpenPGP Library for Android.

Example code

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import android.content.Context;
 
import com.didisoft.pgp.PGPException;
import com.didisoft.pgp.PGPLib;
 
public class SignAndEncryptDemo extends Activity {
 public void signAndEncrypt(Context ctx) throws Exception, PGPException {        
  // create an instance of the library
  PGPLib pgp = new PGPLib();
 
  InputStream dataStream = null;
  InputStream privateSigningKeyStream = null;
  InputStream publicEncryptionKeyStream = null;
  OutputStream outStream = null;        
  try {            
	AssetManager assets = ctx.getAssets();       
	// load data and private key stream
	dataStream = assets.open(INPUT_txt);
	privateSigningKeyStream = assets.open(private_key);
 
	// load the public key of the recipient
	publicEncryptionKeyStream = assets.open(key2_public);
 
        // specify output stream
	outStream = ctx.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;
 
	// call the encrypt method
	pgp.signAndEncryptStream(dataStream, 
				internalFileNameLabel, 
				privateSigningKeyStream, 
				private_key_password,
				publicEncryptionKeyStream,
				outStream, 
				asciiArmor,
				withIntegrityCheck);
   } finally {
       // cleanup
	if (dataStream != null) {
		dataStream.close();
	}
	if (privateSigningKeyStream != null) {
		privateSigningKeyStream.close();
	}
	if (publicEncryptionKeyStream != null) {
		publicEncryptionKeyStream.close();
	}            
	if (outStream != null) {
		outStream.close();
	}
   }
 }
}

The whole example is available in the /Examples/src/android folder contained in the library distribution archive in the file SignAndEncryptDemo.java

Summary

This sample demonstrated how to OpenPGP sign and encrypt in one pass a file in Android.

List of methods used:
PGPLib.signAndEncryptStream