Friday, January 24, 2014

DES Encryption Example using Java

In this post I will give an example about using DESEncryption in java; Data Encryption Standard.

You need to Instantiate the DES key using KeyGenerator class, after that read the generated key into SecretKey class.

1.       Create the DES key
2.       Instantiate an instance of Cipher class, which provides the functionality of cryptographic cipher for encryption.
3.       Initialize the cipher encrypt mode using provided constants.  ENCRYPT_MODE.
4.       Read the text you want to encrypt, and convert it to an array of bytes.
5.       Call doFinal method of cipher instance, and pass your converted array of bytes to this method.
6.       If you want to decrypt, reinitialize the cipher instance to the DECREPT_MODE.
7.       Call doFinal method of cipher instance, and pass your encrypted text to this method.

Following is the full example of the above illustration.

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 DESEncryption {
        public static void main(String[] args) {
            try {
                /** Initialize the key generator */
                KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
                SecretKey myDesKey = keygenerator.generateKey();
/** Class Cipher provides the functionality of a cryptographic cipher for encryption and decryption */
                Cipher desCipher;
                /** create Cipher class */
                desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
                /** Initialize the cipher for encryption mode */
                desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
                /** Data to be encrypted */
                byte[] toBeEncryptedtext = "Please hide me".getBytes();
                System.out.println("Text : " + new String(toBeEncryptedtext));
                /** Call doFinal method and pass the byte text array for encryption */
                byte[] encryptedText = desCipher.doFinal(toBeEncryptedtext);
                System.out.println("Text Encryted : " + encryptedText);
                 /** reInitialize the cipher for encryption mode */
                 desCipher.init(Cipher.DECRYPT_MODE, myDesKey);

                 /** call doFinal method to decrypt the text */
                 byte[] textDecrypted = desCipher.doFinal( encryptedText );
                 System.out.println("Decryted Text: " + new String(textDecrypted));
                } catch(NoSuchAlgorithmException e){
                } catch(NoSuchPaddingException e){
                } catch(InvalidKeyException e){
                } catch(IllegalBlockSizeException e){
                } catch(BadPaddingException e){

In next post, I will provide another way of encryption using web logic mechanism.