Java DES Algorithm Program

Filed Under: Java

Java Cryptography Extension (JCE) provides framework and implementation for generating key and encryption/decryption of data using various algorithms. In this tutorial, we will use Java DES implementation to encrypt and decrypt a file.

DES is a block cipher algorithm in which we will have to use same key for encryption and decryption. It is one of the basic cypher technique. It’s not safe because we need to give client application secure key to decrypt data.

Java DES Encryption Decryption Steps

  • First of all we need to get the KeyGenerator instance using DES algorithm.
  • Generate SecureKey (key) that will be used for encryption and decryption.
  • Get Cipher instance using DES algorithm, one for encrypt mode and another for decrypt mode. Initialize the cypher object using key and IvParameterSpec object.
  • For encryption, create object of CipherOutputStream using encrypt cipher. For decryption, create object of CipherInputStream using decrypt cipher.
  • Read the input stream and write to the output stream.

Below example first encrypt the file and save encrypted data to new file. Then it decrypts the same file to create the plain text file.

package com.journaldev.des;


import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

public class DESEncryptionExample {
	private static Cipher encryptCipher;
	private static Cipher decryptCipher;
	private static final byte[] iv = { 11, 22, 33, 44, 99, 88, 77, 66 };

	public static void main(String[] args) {
		String clearTextFile = "/Users/pankaj/source.txt";
		String cipherTextFile = "/Users/pankaj/cipher.txt";
		String clearTextNewFile = "/Users/pankaj/source-new.txt";

		try {
			// create SecretKey using KeyGenerator
			SecretKey key = KeyGenerator.getInstance("DES").generateKey();
			AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);

			// get Cipher instance and initiate in encrypt mode
			encryptCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			encryptCipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);

			// get Cipher instance and initiate in decrypt mode
			decryptCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			decryptCipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

			// method to encrypt clear text file to encrypted file
			encrypt(new FileInputStream(clearTextFile), new FileOutputStream(cipherTextFile));

			// method to decrypt encrypted file to clear text file
			decrypt(new FileInputStream(cipherTextFile), new FileOutputStream(clearTextNewFile));
		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
				| InvalidAlgorithmParameterException | IOException e) {


	private static void encrypt(InputStream is, OutputStream os) throws IOException {

		// create CipherOutputStream to encrypt the data using encryptCipher
		os = new CipherOutputStream(os, encryptCipher);
		writeData(is, os);

	private static void decrypt(InputStream is, OutputStream os) throws IOException {

		// create CipherOutputStream to decrypt the data using decryptCipher
		is = new CipherInputStream(is, decryptCipher);
		writeData(is, os);

	// utility method to read data from input stream and write to output stream
	private static void writeData(InputStream is, OutputStream os) throws IOException {
		byte[] buf = new byte[1024];
		int numRead = 0;
		// read and write operation
		while ((numRead = >= 0) {
			os.write(buf, 0, numRead);


Once program terminates, you can check that both the plain text file have same data and the encrypted file don’t have plain text data. Below is the files content from my sample files, with cipher text highlighted.

des program in java, des algorithm java, Java DES

Further Reading: Generate CSR Java Program

References: Wikipedia and Java Cryptography Architecture


  1. saeed says:

    Lab Exam – Program for Cryptography

    This is a simple program ( in java) to test the cryptographic by using DES, in which the program
    gets the message and encrypt it to generate cipher text, finally it decrypts the cipher
    text to regenerate again the same message.
    Writing the following program and test it. Getting aware with the interface and the platform.

    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.BadPaddingException;
    public class DESCryptoTest
    public static void main(String[] args)
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    KeyGenerator kg = KeyGenerator.getInstance(“DES”);
    Key key = kg.generateKey();
    Cipher cipher = Cipher.getInstance(“DES”);
    byte[] data = “This is an example of DES Encryption and Decryption!”.getBytes();
    System.out.println(“Original data : ” + new String(data));
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] result = cipher.doFinal(data);
    System.out.println(“Encrypted data: ” + new String(result));
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] original = cipher.doFinal(result);
    System.out.println(“Decrypted data: ” + new String(original));
    catch (NoSuchAlgorithmException e)
    catch (NoSuchPaddingException e)
    catch (InvalidKeyException e)
    catch (IllegalStateException e)
    catch (IllegalBlockSizeException e)
    catch (BadPaddingException e)
    e.printStackTrace(); }

    What is the output of the above program? 2.5 pts
    What do you observe? 2.5 pts

    Modify the above code and use AES encryption algorithm as the Encryption Mode. After you modify the code, ensure it is working fine and past it below. 5 pts

  2. Dipali says:

    hello sir
    i try t execute the program but there was an error
    that main class is not find and load please help me

  3. kausalya says:

    Thank u so much……It worked…..

  4. ajay says:

    Can we do the same with string instead of a file?

  5. betelhem says:

    sir i’m having a problem on " it says i have to create local variable

  6. anbuselvi says:

    Hi sir,

    I followed your posts from recent years, it’s very helpful to me .
    nice keep going…..

  7. Rizki Yuniar says:

    Sir how can I find for the block diagram inisal permutations..?

  8. Bibhuti says:

    Hi Pankaj,

    First of all I would like to thanks, because most of the post of this site is helping out to us.

    However when i looked into this code “Java DES Encryption Decryption”
    I am interested to run and test this in two different Scenario

    1. run both Encryption and Decryption at a time – work fine
    2. run first Encryption and then Decryption – Failed (it does not decrypt it encrypt again)

    can you please help me out why it is ?


    1. Pankaj says:

      Basically both your point 1 and 2 are same thing, I am not sure what you are trying to say.

  9. MIHIR says:

    its so usefull great man . your code is perfect . i am very so thank full to you pankaj…:))))

  10. rami says:

    hi Pankaj, works fine..i got the error and i solved it…. Thank you so much

  11. rami says:

    Dear pankaj,

    I used this code there is an error in catch statement that “multi-catch statement is not supported in -source 1.6 (use -source 7 or higher to enable multi-catch statement)”

    please help me to make the code correct

    1. Virendra Singh says:

      Hi rami,

      Can you see in the code that to handle the code exceptions he has written different Exception types in the catch block using logical OR (|).

      catch (NoSuchAlgorithmException |
      NoSuchPaddingException |
      InvalidKeyException |
      InvalidAlgorithmParameterException |
      IOException e) {

      Just change it to different catch{} blocks.
      It should resolve your issue.

  12. Mithun says:

    Hi Pankaj,

    Can you explain me how to encrypt a message in java code with example


  13. Helder says:

    Do you thought about synchronization problems? Shouldn’t the methods “encrypt” and “decrypt” be synchronized?

    1. Pankaj says:

      This is example to show how we can use it, if I go into all other details we will loose focus on the topic.

  14. maxpayne says:

    Thanks for this code … nice work

    1. Pankaj says:

      You are welcome Max.

  15. maxpayne says:

    hello ,Pankaj this code works fine thanks for this post..

  16. Satheeshkumar says:

    Hi Sir, The above example work nicely but when i use separate function i.e) Fist time i upload a normal file, when i upload a file it encrypted and save on one location. Again i upload the encrypted file to decrypt that file not show the same content in normal file. What i do ? kindly guide me. Thank You

    1. Pankaj says:

      Is the decrypted file totally garbage or some of the content is not decrypted correctly. Sometimes the Text Editor programs add their own styling that may cause this.

      1. Satheeshkumar says:

        Hi sir, First time i encrypt the file that time encryptCipher and decryptCipher look like encryptCipher = javax.crypto.Cipher@12331d5 decryptCipher = javax.crypto.Cipher@19cbb6f, after i upload file to decrypt the content it used encryptCipher = javax.crypto.Cipher@12331d5
        decryptCipher = javax.crypto.Cipher@19cbb6f. So i save decryptCipher in one temporary
        cipher to decrypt the file the content will display. Finally i need how to save and read the javax.crypto.Cipher@19cbb6f i don’t know please guide me.

      2. Satheeshkumar says:

        Hi Sir, Exactly what i want means i want to save decryptCipher in file, after i will decrypt the file first it read the decryptCipher after i call is = new CipherInputStream(is, decryptCipher);

  17. navrang pal kaur says:

    hello sir…. i have a problem. i am usig this code in eclipse juno. there are some errors. i am new to java programming. please help me. i am posting the errors here. please suggest now what to do. \Users\pankaj\source.txt (The system cannot find the path specified)
    at Method)
    at DES.main(

    1. Pankaj says:

      You need to modify the program and pass file location correctly, i am sure its not “\Users\pankaj\source.txt” for you.

  18. Prateek says:

    Good work Pankaj..really helped me…thanks a lot and keep writing..

    1. Pankaj says:

      Thanks Prateek, these comments pushes me to keep continuing…

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages