Thursday, 15 August 2013

Asymmetric Key Encryption / Decryption

In the previous chapter we saw how we can encrypt and decrypt data using symmetric key.

Here we are going to use private/public key pair for encryption and decryption.

In Asymmetric key encryption/decryption both parties do not need to share the same key with each other. The private key is with the authoring party and it can distribute the public key generated from private key to users. This will add more security constraint on the private key tampering.

In the below example we use the KeyPairGenerator class to create private and public key. To generate the key pair using key tool refer Java Asymmetric Key Keytool.

The KeyPairGenerator is instantiated with RSA algorithm. Any of the below algorithm can also be used.
DiffieHellman (1024)
DSA (1024)
RSA (1024, 2048)
And than we use the Cipher class to encrypt and decrypt the data as explained in the previous example.

For a maven project you will need the apache-common-codec jar as a dependency or else just download the jar and paste it in the folder which is in the classpath.

Maven dependency:
<dependency>
 <groupId>commons-codec</groupId>
 <artifactId>commons-codec</artifactId>
 <version>1.8</version>
</dependency>

Main Class
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

public class AssymmetricKey {
 public static void main(String[] args) throws Exception {

  KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
  keyPairGenerator.initialize(1024);
  KeyPair keyPair = keyPairGenerator.generateKeyPair();
  PrivateKey privateKey = keyPair.getPrivate();
  PublicKey publicKey = keyPair.getPublic();

  String dataToBeEncrypted = "MyHome";

  Cipher cipher = Cipher.getInstance("RSA");

  cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  String encryptedData =Base64.encodeBase64String(cipher.doFinal(dataToBeEncrypted.getBytes())); 
  System.out.println("Encrypted Data: " + encryptedData);
  
  Cipher dipher = Cipher.getInstance("RSA");

  dipher.init(Cipher.DECRYPT_MODE, privateKey);
  System.out.println(new String(dipher.doFinal(Base64.decodeBase64(encryptedData))));
  
  
  

 }
}


Java Examples

No comments:

Post a comment

Share the post