Java - DES Encryption and Decryption with example

The Data Encryption Standard  is a symmetric-key algorithm for the encryption of electronic data. Although its short key length of 56 bits, criticized from the beginning, makes it too insecure for most current applications, it was highly influential in the advancement of modern cryptography.

Developed in the early 1970s at IBM and based on an earlier design by Horst Feistel, the algorithm was submitted to the National Bureau of Standards (NBS) following the agency's invitation to propose a candidate for the protection of sensitive, unclassified electronic government data. In 1976, after consultation with the National Security Agency (NSA), the NBS eventually selected a slightly modified version (strengthened against differential cryptanalysis, but weakened against brute-force attacks), which was published as an official Federal Information Processing Standard (FIPS) for the United States in 1977.

Example:


package com.knowledgefactory;


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

class DES {
Cipher ecipher;

Cipher dcipher;

DES(SecretKey key) throws Exception {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}

public String encrypt(String str) throws Exception {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");

// Encrypt
byte[] enc = ecipher.doFinal(utf8);

// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}

public String decrypt(String str) throws Exception {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

byte[] utf8 = dcipher.doFinal(dec);

// Decode using utf-8
return new String(utf8, "UTF8");
}

public static void main(String[] argv) throws Exception {
final String secretText = "www.knowledgefactory.net";
System.out.println("SecretText: " + secretText);
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
DES encrypter = new DES(key);
String encrypted = encrypter.encrypt(secretText);
System.out.println("Encrypted Value: " + encrypted);
String decrypted = encrypter.decrypt(encrypted);
System.out.println("Decrypted: " + decrypted);

}
}

Output:



SecretText: www.knowledgefactory.net
Encrypted Value: aoZpR3t1ikFrFrEHzrqrwcEdAyssGcY3W/P5eAjAANo=
Decrypted: www.knowledgefactory.net


This article is contributed by Sibin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Comments