Home » Core Java » crypto » Encrypt/Decrypt with DES using pass phrase

About Byron Kiourtzoglou

Byron Kiourtzoglou
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Encrypt/Decrypt with DES using pass phrase

With this example we are going to demonstrate how to encrypt/decrypt with DES using a password phrase. DES in computing refers to the Data Encryption Standard and is supported by Java. In short, to encrypt/decrypt with DES using a password phrase you should:

  • Create a String password that can be used with password-based encryption (PBE).
  • Provide password, salt, iteration count for generating PBEKey of fixed-key-size PBE Ciphers.
  • Create a SecretKey using PBE with MD5 and DES.
  • Construct a AlgorithmParameterSpec for password-based encryption as defined in the PKCS #5 standard.
  • Initialize two Ciphers, one in encryption mode and the other one in decryption mode. Use them to encrypt the String message and then decrypt the encrypted String.
  • The encryption is performed in the String encrypt(String str) method. It encodes the string into a sequence of bytes using the named charset, storing the result into a new byte array. Then it calls doFinal(byte[] input) API method of Cipher to make the encryption. It uses the com.sun.mail.util.BASE64EncoderStream to encode the encrypted byte array and returns the String created from the byte array.
  • The decryption is performed in the String decrypt(String str) method. It uses the com.sun.mail.util.BASE64DecoderStream to decode the String to byte array. Then it calls doFinal(byte[] input) API method of Cipher to make the decryption. It creates a new string based on the specified charset from the decrypted byte array.
  • You can handle exceptions like InvalidAlgorithmParameterException, InvalidKeySpecException, NoSuchAlgorithmException
    InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

import com.sun.mail.util.BASE64DecoderStream;
import com.sun.mail.util.BASE64EncoderStream;

public class EncryptDecryptWithDESUsingPassPhrase {

	private static Cipher ecipher;
	private static Cipher dcipher;

	private static final int iterationCount = 10;

	// 8-byte Salt
	private static byte[] salt = {

  (byte)0xB2, (byte)0x12, (byte)0xD5, (byte)0xB2,

  (byte)0x44, (byte)0x21, (byte)0xC3, (byte)0xC3
    };

	public static void main(String[] args) {

		try {

			String passPhrase = "My Secret Password";

			// create a user-chosen password that can be used with password-based encryption (PBE)
			// provide password, salt, iteration count for generating PBEKey of fixed-key-size PBE ciphers
			KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);

			// create a secret (symmetric) key using PBE with MD5 and DES 
			SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);

			// construct a parameter set for password-based encryption as defined in the PKCS #5 standard
			AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

			ecipher = Cipher.getInstance(key.getAlgorithm());
			dcipher = Cipher.getInstance(key.getAlgorithm());

			// initialize the ciphers with the given key

  ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);

  dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

  String encrypted = encrypt("This is a classified message!");

  String decrypted = decrypt(encrypted);

  System.out.println("Decrypted: " + decrypted);

		}
		catch (InvalidAlgorithmParameterException e) {
			System.out.println("Invalid Alogorithm Parameter:" + e.getMessage());
			return;
		}
		catch (InvalidKeySpecException e) {
			System.out.println("Invalid Key Spec:" + e.getMessage());
			return;
		}
		catch (NoSuchAlgorithmException e) {
			System.out.println("No Such Algorithm:" + e.getMessage());
			return;
		}
		catch (NoSuchPaddingException e) {
			System.out.println("No Such Padding:" + e.getMessage());
			return;
		}
		catch (InvalidKeyException e) {
			System.out.println("Invalid Key:" + e.getMessage());
			return;
		}

	}

	public static String encrypt(String str) {

  try {

  	// encode the string into a sequence of bytes using the named charset

  	// storing the result into a new byte array. 

  	byte[] utf8 = str.getBytes("UTF8");

byte[] enc = ecipher.doFinal(utf8);

// encode to base64

enc = BASE64EncoderStream.encode(enc);

return new String(enc);

  }

  catch (Exception e) {

  	e.printStackTrace();

  }

  return null;

    }

	public static String decrypt(String str) {

  try {

  	// decode with base64 to get bytes

byte[] dec = BASE64DecoderStream.decode(str.getBytes());

byte[] utf8 = dcipher.doFinal(dec);

// create new string based on the specified charset

return new String(utf8, "UTF8");

  }

  catch (Exception e) {

  	e.printStackTrace();

  }

  return null;

    }

}

Output:

Decrypted: This is a classified message!

 
This was an example of how to encrypt/decrypt with DES using a password phrase in Java.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of