Pages

Wednesday, August 1, 2012

Text Encryption/Decryption using JCE(Java Cryptography Extension) API

Hi Guys,

There are some cases where you need to encrypt some data like passwords.
At that time for server-side encryption and decryption; you need to use JCE (Java Cryptography Extension) API.

The JCE API covers:
  • Symmetric bulk encryption, such as DES, RC2, and IDEA
  • Symmetric stream encryption, such as RC4
  • Asymmetric encryption, such as RSA
  • Password-based encryption (PBE)
  • Key Agreement
  • Message Authentication Codes (MAC)
To use JCE API, you need following jar files, required to add in your project build path.


  • jce1_2_2.jar
  • local_policy.jar
  • sunjce_provider.jar
  • US_export_policy.jar

After adding JARs in build path, you can use the classes and interfaces of JCE API.
Here is the sample code for encrypting and decryption of simple text with DES algorithm using JCE API.


import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

public class EncryptDecrypt {
public static void main(String args[]) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher desCipher = Cipher.getInstance("DES");
KeyGenerator myKey = KeyGenerator.getInstance("DES");
SecretKey desKey = myKey.generateKey();
desCipher.init(Cipher.ENCRYPT_MODE, desKey);

byte[] cleartext = "DHAVAL SHAH".getBytes();
byte[] ciphertext = desCipher.doFinal(cleartext);

System.out.println("Encrypted Text:  "+new String(ciphertext));
// Initialize the same cipher for decryption
desCipher.init(Cipher.DECRYPT_MODE, desKey);

// Decrypt the ciphertext
byte[] cleartext1 = desCipher.doFinal(ciphertext);
System.out.println("Decrypted Text:  "+new String(cleartext1));

}
}


OUTPUT:




To Explore more on JCE API, refer this link:



No comments:

Post a Comment