With the increase awareness to security the demand for securing data is rising. Fortunately Java provides pretty good tools that can help developers encrypt and decrypt data.
One of the most popular encryption is called RSA encryption. Named after its inventors, Ron Rivest, Adi Shamir and Leonard Adleman, RSA encryption transforms the number “char” into the number “cipher” with the formula
cipher = char^e (mod n)
The numbers e and n are the two numbers you create and publish. They are your “public key.” The number char can be simply the digital value of a block of ASCII characters. The formula says: multiply the number char by itself e times, then divide the result by the number n and save only the remainder. The remainder that we have called cipher is the encrypted representation of char.
Using the two numbers you have published, anyone can scramble a message and send it to you. You are the only one who can unscramble it; not even the sender of the message can decrypt the ciphertext.
Standard Java 2 distribution includes security provider support for generation of RSA digital signatures, but does NOT contain a provider implementation for generating RSA encrypted data. An extra provider must be added to obtain this capability from standard Java 2, such as the Bouncy Castle Provider.
Since I couldn’t find any good examples that use Java with RSA, we’ll build a nice RSAEncryptUtil class that you can use as a reference for using RSA encryption (you can download the full source code here).
The first thing we need to do is to define the algorithm that we want to use.
protected static final String ALGORITHM = "RSA";
Then as stated before we’ll need to add Bouncy Castle as our RSA provider. In order to do that we’ll write an Init method for our class
/**
* Init java security to add BouncyCastle as an RSA provider
*/
public static void init()
{
Security.addProvider(new BouncyCastleProvider());
}
To generate what is called private and public keys, Java provides us with a simple to use KeyPairGenerator class. The java.security.KeyPairGenerator generates the two keys that are returned in a java.security.KeyPair object.
/**
* Generate key which contains a pair of privae and public key using 1024 bytes
* @return key pair
* @throws NoSuchAlgorithmException
*/
public static KeyPair generateKey() throws NoSuchAlgorithmException
{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
return key;
}