security

Encrypt/Decrypt a file using DES

In this example we shall show you how to encrypt/decrypt a file using DES. To encrypt and decrypt a file using the Data Encryption Standard Algorithm, one should perform the following steps:

  • Create a KeyGenerator for the DES algorithm and generate a secret key.
  • Create an IvParameterSpec object, which is an implementation of the AlgorithmParameterSpec Interface, a specification of cryptographic parameters.
  • Create two Cipher objects, one to implement the encryption and the other one for the decryption. Both Ciphers must be initialized to encryption/decryption mode, with the key and the algorithm parameters defined above.
  • Create a FileInputStream to read the file to be encrypted and a FileOutputStream to write the encrypted file.
  • Read data from a FileInputStream into a byte array.
  • Encrypt the byte array. Create a new CipherOutputStream using the encryption cipher and the byte array. The CipherOutputStream encrypts data before writing it out to an OutputStream, as shown in the write_encode(byte[], Outputstream output) method of the example.
  • Create a FileInputStream to read the above encrypted file that will now be descrypted.
  • Decrypt the file. Create a new CipherInputStream using the decryption cipher and the byte array .The CipherInputStream will read in the byte array and decrypt each byte before returning it. This is demonstrated in the read_decode(byte[], InputStream input) method of the example.

Let’s take a look at the code snippet that follows.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
package com.javacodegeeks.snippets.core;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
 
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
 
public class Main {
 
    static Cipher ce;
    static Cipher cd;
 
    public static void main(String args[]) throws Exception {
 
  Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
 
  SecretKey skey = KeyGenerator.getInstance("DES").generateKey();
 
  byte[] initializationVector = new byte[]{0x10, 0x10, 0x01, 0x04, 0x01, 0x01, 0x01, 0x02};
 
  AlgorithmParameterSpec algParameters = new IvParameterSpec(initializationVector);
 
  ce = Cipher.getInstance("DES/CBC/PKCS5Padding");
 
  cd = Cipher.getInstance("DES/CBC/PKCS5Padding");
 
  ce.init(Cipher.ENCRYPT_MODE, skey, algParameters);
 
  cd.init(Cipher.DECRYPT_MODE, skey, algParameters);
 
  FileInputStream is = new FileInputStream("C:/Users/nikos7/Desktop/output.txt");
 
  FileOutputStream os = new FileOutputStream("C:/Users/nikos7/Desktop/output2.txt");
 
  int dataSize = is.available();
 
  byte[] inbytes = new byte[dataSize];
 
  is.read(inbytes);
 
  String str2 = new String(inbytes);
 
  System.out.println("Input file contentn" + str2 + "n");
 
  write_encode(inbytes, os);
 
  os.flush();
 
  is.close();
 
  os.close();
 
  System.out.println("Ecrypted Content to output2.txtn");
 
  is = new FileInputStream("C:/Users/nikos7/Desktop/output2.txt");
 
  byte[] decBytes = new byte[dataSize];
 
  read_decode(decBytes, is);
 
  is.close();
 
  String str = new String(decBytes);
 
  System.out.println("Decrypted file contents:n" + str);
 
    }
 
    public static void write_encode(byte[] bytes, OutputStream output) throws Exception {
 
  CipherOutputStream cOutputStream = new CipherOutputStream(output, ce);
 
  cOutputStream.write(bytes, 0, bytes.length);
 
  cOutputStream.close();
    }
 
    public static void read_decode(byte[] bytes, InputStream input) throws Exception {
 
  CipherInputStream cInputStream = new CipherInputStream(input, cd);
 
  int position = 0, i;
 
  while ((i = cInputStream.read()) != -1) {
 
bytes[position] = (byte) i;
 
position++;
 
  }
    }
}

Output:

Input file content Some programs have a clear design and coding new features is quick and easy. Other programs are a patchwork quilt of barely comprehensible fragments, bug fixes, and glue. If you have to code new features for such programs, you're often better off rewriting them. Ecrypted Content to output2.txt Decrypted file contents: Some programs have a clear design and coding new features is quick and easy. Other programs are a patchwork quilt of barely comprehensible fragments, bug fixes, and glue. If you have to code new features for such programs, you're often better off rewriting them.

 
This was an example of how to encrypt an decrypt a file using the DES algorithm in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He 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
Anastasiia
Anastasiia
6 years ago

very interesting example, but I stacked at the point of importing bouncy castle, it just says that can’t find the lib

Back to top button