crypto

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.

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Zizzy
5 years ago

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 »

Back to top button