Main Tutorials

JCE Encryption – Data Encryption Standard (DES) Tutorial

In this article, we show you how to use Java Cryptography Extension (JCE) to encrypt or decrypt a text via Data Encryption Standard (DES) mechanism.

1. DES Key

Create a DES Key.


    KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
    SecretKey myDesKey = keygenerator.generateKey();

2. Cipher Info

Create a Cipher instance from Cipher class, specify the following information and separated by a slash (/).

  • Algorithm name
  • Mode (optional)
  • Padding scheme (optional)

    Cipher desCipher;
    // Create the cipher 
    desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
Note
DES = Data Encryption Standard.
ECB = Electronic Codebook mode.
PKCS5Padding = PKCS #5-style padding.

In this case, you created a DES (Data Encryption Standard) cipher in Electronic Codebook mode, with PKCS #5-style padding.

3. Convert It

Convert String into Byte[] array format.


    byte[] text = "No body can see me".getBytes();

4. Encrypt It

Make Cipher in encrypt mode, and encrypt it with Cipher.doFinal() method.


    desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
    byte[] textEncrypted = desCipher.doFinal(text);

5. Decrypt It

Make Cipher in decrypt mode, and decrypt it with Cipher.doFinal() method as well.


    desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
    byte[] textDecrypted = desCipher.doFinal(textEncrypted);

6. Full Example

Full Example to show how to use Java’s JCE to encrypt and decrypt text in DES mechanism.


package com.mkyong.util;

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 JEncrytion
{    
	public static void main(String[] argv) {
		
		try{

		    KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
		    SecretKey myDesKey = keygenerator.generateKey();
		    
		    Cipher desCipher;

		    // Create the cipher 
		    desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		    
		    // Initialize the cipher for encryption
		    desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);

		    //sensitive information
		    byte[] text = "No body can see me".getBytes();

		    System.out.println("Text [Byte Format] : " + text);
		    System.out.println("Text : " + new String(text));
		   
		    // Encrypt the text
		    byte[] textEncrypted = desCipher.doFinal(text);

		    System.out.println("Text Encryted : " + textEncrypted);
		    
		    // Initialize the same cipher for decryption
		    desCipher.init(Cipher.DECRYPT_MODE, myDesKey);

		    // Decrypt the text
		    byte[] textDecrypted = desCipher.doFinal(textEncrypted);
		    
		    System.out.println("Text Decryted : " + new String(textDecrypted));
		    
		}catch(NoSuchAlgorithmException e){
			e.printStackTrace();
		}catch(NoSuchPaddingException e){
			e.printStackTrace();
		}catch(InvalidKeyException e){
			e.printStackTrace();
		}catch(IllegalBlockSizeException e){
			e.printStackTrace();
		}catch(BadPaddingException e){
			e.printStackTrace();
		} 
	   
	}
}

Output


Text [Byte Format] : [B@19b5393
Text : No body can see me
Text Encryted : [B@4e79f1
Text Decryted : No body can see me

Reference

  1. JavaTM Cryptography Architecture – http://java.sun.com/j2se/1.5.0/docs/guide/security/CryptoSpec.html

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
26 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Raj
4 years ago

Cipher is not thread-safe. Is there any solution to use the Cipher (with single instance) in a multi-threading environment apart from synchronized block.

Jatin Ghataliya
8 years ago

while i am gone decrypt the string i got following exception :

Exception : while decryption : javax.crypto.BadPaddingException: Given final block not properly padded

Luis
5 years ago

Superb

WhatsInName
6 years ago

Not useful with Updated Java version. Kindly update your tutorial.

AVINASH MISHRA
7 years ago

What if I want the user to enter their own key while encryption and use that key to decrypt?

Patrick
7 years ago

Really helpful thanks 🙂

DavisJozk
8 years ago

Simple and cool
Keep it up!

samasim
10 years ago

what type of algorithm did you use ?

Michael Balanov
10 years ago

Thanks a lot for the article. Can you please tell how I can save and then restore generated key? I need to save it in file or hardcoded constant.

Michael Balanov
10 years ago

I’ve just found an answer. )

// save key
byte[] key = myDesKey.getEncoded();

// restore key
myDesKey = new SecretKeySpec(key, “DES”);

Shankar Kumara
10 years ago

@mkyoung
This example gives encrypt and decrypt using standards.
I have to encrypt using public certificate and decrypt using private certificate.

Will you be able to provide sample fo the above?

peter
11 years ago

nice post.. but i got error javax.crypto.IllegalBlockSizeException: last block incomplete in decryption

peter
11 years ago

javax.crypto.IllegalBlockSizeException: last block incomplete in decryption

peter
11 years ago

Hi nice post, but i need separate method encryption and decryption but i got error like “javax.crypto.IllegalBlockSizeException: last block incomplete in decryption” pl.help on this

saba
11 years ago

it s veryusefull

saba
11 years ago

it’s vey usefull….. thanks lot

Srinivasa HP
11 years ago

I need to know how to do encyption at the server side (JAX-rs service). well, i was able to do but the size of the byte is getting increased from 128 to 638 due to which i am unable to decrypt. Pls help me in this regard

BINOY KUMAR BARANWAL
11 years ago

This program is excellent. Now I came to know why Java is so powerful. Thanks…..

Ivan S. Acog
12 years ago

this post was vary helpful.. thank you

Ganda
13 years ago

Thanks for information, can l reguest your program complete?
because theprogram important for me to help mystudy.
thank you very much….

Dipongker Sen
6 years ago
Reply to  mkyong

Sir,
Can you help me to this code with user input like user can give a secret key or can input a message?
I’m trying but its not working. So, please if you help me to overcome from this, I’m very respectful to you.
Thankful

skvmb
13 years ago

Thank you for this post. Very helpful information.

Kevin
15 years ago

pretty cool!

Hari Shankar Maurya
11 years ago
Reply to  Kevin

This Example is so helpful to me.can u give some example or link which are provided by another third party tool used in java or more effextive than this java cryptography….do u think this is enough for data security.

RR
10 years ago

Hi, thanks for your sample code.
I’m not sure what if I would like to change key, if I change this
KeyGenerator.getInstance(“DES”);

to this
KeyGenerator.getInstance(“ThisIsMyKey”);

Is that right way to use my own key ?

Thank you~