RSA Encryption using your Public and Private key how to / example

by New Developer on ‎03-27-2013 04:20 PM (4,873 Views)

Here's a quick sample showing how to encrypt using RSA®. When you encrypt with the public key, only the holder of the private key can decrypt it.

 

Remember though - every time you encrypt the same data with the same key - the output will be the same - perfect for an eavesdropper to notice!

 

Encrypting;

 

// Get the public key from a PEM encoded RSA certificate
InputStream stream = getClass().getResourceAsStream("sams.crt");
byte[] base64bytes = new byte[stream.available()];
stream.read(base64bytes, 0, base64bytes.length);
stream.close();

X509Certificate cert = (X509Certificate) CertificateUtilities.readCertificateFile("X509", base64bytes);
pubKey = (RSAPublicKey) cert.getPublicKey();

//Initiate the Crypto system
RSACryptoSystem crypt = crypt = new RSACryptoSystem(2048);  //I used 2048 bits keys

 

An now an example method howto encrypt data and return a Base64 string of the encrypted value.

 

//Example method to encrypt data with the above objects
public String encrypt(String data){
	try{	
		if(data.length() > 0){
			NoCopyByteArrayOutputStream out = new NoCopyByteArrayOutputStream();
			data = data.trim();
			byte[] plain = data.getBytes();		
			RSAEncryptorEngine eng = new RSAEncryptorEngine(this.pubKey);
			PKCS1FormatterEngine fengine = new PKCS1FormatterEngine(eng);
			
			BlockEncryptor cryptoStream = new BlockEncryptor(fengine, out);
			cryptoStream.write( plain, 0, plain.length );
			cryptoStream.flush();
			cryptoStream.close();
			out.close();
			
			byte[] cipherText = out.getByteArray();
			
			String encMessage = Base64OutputStream.encodeAsString(cipherText, 0, cipherText.length, false, false);
			return encMessage;
		}else{
			return "";
		}
	}
	catch(Exception err){
		System.err.println(err.toString());
		return "";
	}
}