Ilias Tsagklis

About Ilias Tsagklis

Ilias Tsagklis is a senior software engineer working in the telecom domain. He is an applications developer in a wide variety of applications/services. Ilias is co-founder and Executive Editor at Java Code Geeks.

Encrypt/Decrypt file/stream with DES

This is an example of how to encrypt or decrypt a file or stream with DES. DES in computing refers to the Data Encryption Standard and is supported by Java. To encrypt or decrypt a file or stream with DES one should perform the following steps:

These are demonstrated in the code snippet(s) below:

package com.javacodegeeks.snippets.core;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;

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 EncryptDecryptFileStreamWithDES {

	private static Cipher ecipher;
	private static Cipher dcipher;

	// 8-byte initialization vector
	private static byte[] iv = {

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

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

	public static void main(String[] args) {

		try {

			SecretKey key = KeyGenerator.getInstance("DES").generateKey();

			AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);

			ecipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

dcipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

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

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

encrypt(new FileInputStream("cleartext.txt"), new FileOutputStream("encrypted.dat"));

decrypt(new FileInputStream("encrypted.dat"), new FileOutputStream("cleartext-reversed.txt"));

		}
		catch (FileNotFoundException e) {
			System.out.println("File Not Found:" + e.getMessage());
			return;
		}
		catch (InvalidAlgorithmParameterException e) {
			System.out.println("Invalid Alogorithm Parameter:" + 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;
		}

	}

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

  try {

  	byte[] buf = new byte[1024];

// bytes at this stream are first encoded

  	os = new CipherOutputStream(os, ecipher);

// read in the clear text and write to out to encrypt

int numRead = 0;

while ((numRead = is.read(buf)) >= 0) {

    os.write(buf, 0, numRead);

}

// close all streams

os.close();

  }

  catch (IOException e) {

  	System.out.println("I/O Error:" + e.getMessage());

  }

    }

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

  try {

  	byte[] buf = new byte[1024];

// bytes read from stream will be decrypted

  	CipherInputStream cis = new CipherInputStream(is, dcipher);

// read in the decrypted bytes and write the clear text to out

int numRead = 0;

while ((numRead = cis.read(buf)) >= 0) {

    os.write(buf, 0, numRead);

}

// close all streams

cis.close();

is.close();

os.close();

  }

  catch (IOException e) {

  	System.out.println("I/O Error:" + e.getMessage());

  }

    }

}

This was an example of how to Encrypt/Decrypt file/stream with DES.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books