Home » Core Java » crypto » Encrypt/Decrypt string with DES

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 string with DES

In this example we shall show you how to encrypt and decrypt a String with DES. DES in computing refers to the Data Encryption Standard and is supported by Java. To encrypt and decrypt a String with DES one should perform the following steps:

  • Generate a SecretKey using DES algorithm, with the KeyGenerator generateKey() API method.
  • 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,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

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

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

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

public class EncryptDecryptStringWithDES {

	private static Cipher ecipher;
	private static Cipher dcipher;

	private static SecretKey key;

	public static void main(String[] args) {

		try {

			// generate secret key using DES algorithm
			key = KeyGenerator.getInstance("DES").generateKey();

			ecipher = Cipher.getInstance("DES");
			dcipher = Cipher.getInstance("DES");

			// initialize the ciphers with the given key

  ecipher.init(Cipher.ENCRYPT_MODE, key);

  dcipher.init(Cipher.DECRYPT_MODE, key);

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

  String decrypted = decrypt(encrypted);

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

		}
		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 and decrypt a String with DES in Java.

(No Ratings Yet)
1 Comment 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

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Zizzy Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Zizzy
Guest

Thanks! Old article, still relevant. Just needs a few updates: import java.util.Base64; 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 String encString = new String(Base64.getEncoder().encodeToString(enc)); return new String(encString); } catch (Exception e) { e.printStackTrace(); } return null; } public static String decrypt(String str) { try { // decode with base64 to get bytes byte[] dec = Base64.getDecoder().decode(str.getBytes()); byte[] utf8 = dcipher.doFinal(dec); // create new string based… Read more »