13
Nov/10
Follow iNebium on twitter

3DES Encryption in Java and DES Encryption in Java

[13 Nov 10 at 09:23:26 - 5 comment(s)]

Here is a small post with just code to do 3DES (Triple DES) and DES Encryption in Java. You can simply copy/paste it in a Class you call Encrypter and it's ready to use. Simply need to pass the key and the IV as arguments to the public constructor. No more talking, here is the code.

3DES Encryption

import java.security.MessageDigest;
import java.security.spec.KeySpec;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.binary.Base64;

public class Encrypter {
  private KeySpec keySpec;
  private SecretKey key;
  private IvParameterSpec iv;
  
  public Encrypter(String keyString, String ivString) {
    try {
      final MessageDigest md = MessageDigest.getInstance("md5");
      final byte[] digestOfPassword = md.digest(Base64.decodeBase64(keyString.getBytes("utf-8")));
      final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
      for (int j = 0, k = 16; j < 8;) {
        keyBytes[k++] = keyBytes[j++];
      }
      
      keySpec = new DESedeKeySpec(keyBytes);
      
      key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);
      
      iv = new IvParameterSpec(ivString.getBytes());
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
  
  public String encrypt(String value) {
    try {
      Cipher ecipher = Cipher.getInstance("DESede/CBC/PKCS5Padding","SunJCE");
      ecipher.init(Cipher.ENCRYPT_MODE, key, iv);
      
      if(value==null)
        return null;
      
      // Encode the string into bytes using utf-8
      byte[] utf8 = value.getBytes("UTF8");
      
      // Encrypt
      byte[] enc = ecipher.doFinal(utf8);
      
      // Encode bytes to base64 to get a string
      return new String(Base64.encodeBase64(enc),"UTF-8");
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  
  public String decrypt(String value) {
    try {
      Cipher dcipher = Cipher.getInstance("DESede/CBC/PKCS5Padding","SunJCE");
      dcipher.init(Cipher.DECRYPT_MODE, key, iv);
      
      if(value==null)
        return null;
      
      // Decode base64 to get bytes
      byte[] dec = Base64.decodeBase64(value.getBytes());
      
      // Decrypt
      byte[] utf8 = dcipher.doFinal(dec);
      
      // Decode using utf-8
      return new String(utf8, "UTF8");
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}

And that's it for the 3DES encryption.

DES Encryption

If you want to do DES encryption rather than 3DES encryption. There is not much to change. You need to remove the following:

      final MessageDigest md = MessageDigest.getInstance("md5");
      final byte[] digestOfPassword = md.digest(Base64.decodeBase64(keyString.getBytes("utf-8")));
      final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
      for (int j = 0, k = 16; j < 8;) {
        keyBytes[k++] = keyBytes[j++];
      }

Then you replace:

keySpec = new DESedeKeySpec(keyBytes);

key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);

by:

keySpec = new DESKeySpec(password.getBytes("utf-8"));
      
key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);

And finally when you instantiate Cipher, instead of:

Cipher.getInstance("DESede/CBC/PKCS5Padding","SunJCE");

You have:

Cipher.getInstance("DES/CFB/NoPadding","SunJCE");

Done!

Conclusion

We have seen in this post how to do 3DES encryption/decryption as well as DES encryption/decryption. As you can see, it is pretty easy. If you have questions or you think something is not correct in the code, don't hesitate to leave a comment. For more information regarding Triple DES and DES algorithm, go check out wikipedia for 3DES (Triple DES) and DES which stands for Data Encryption Standard.


Add new comment





Notify me of follow up comments

5 Comment(s)

inebium  -  08 Aug 2011 at 11:23:54
down  up
for sombra7, about the import missing on org.apache.commons.codec.binary.Base64;

you are missing a jar.

if you are using maven, you can add this dependency:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.3</version>
</dependency>

inebium  -  08 Aug 2011 at 11:20:55
down  up
You can add the following:
public static void main(String[] args) {

}

M  -  08 Aug 2011 at 10:38:08
down  up
hi
excuse me, I am new to java...when I copy this code,it says that it doesn't have the main method...what should I do to clear this error and be able to run the program?
Thank you

Sombra7  -  10 Jul 2011 at 04:34:19
+1 vote(s) down  up
me da un error al importar la libreria
import org.apache.commons.codec.binary.Base64;
que puedo hacer.. alguien puede ayudarme

I get an error when importing the library
import org.apache.commons.codec.binary.Base64;
I can do .. can someone help

Anonymous  -  03 Apr 2011 at 21:04:48
down  up
Hi,
Thanks for the codes.

The key I use is 21 Bytes and the code gives error mesages in for loop:for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}

Any idea?

Follow the RSS feed Follow the RSS feed

Recent Posts

How to run glxgears at full speed and not synchronized to vertical refresh?
You normally use glxgears to check performance of your graphic card but you get the same as your mon...
15 Nov 11
catalyst 11.10 / gnome-shell still not usable
In my post about catalyst 11.9, I wrote a rant about the AMD catalyst driver which after 6 months we...
01 Nov 11
A list of useful regexp
regexp or in other words regular expression is something you have to regularly use in your applicati...
30 Oct 11
catalyst 11.9 still doesn't work with gnome-shell!
Gnome 3.0 was released on the 6th of April 2011. At the time I write this post, Gnome 3.2 has been r...
29 Sep 11
3DES Encryption in Java and DES Encryption in Java
Here is a small post with just code to do 3DES (Triple DES) and DES Encryption in Java. You can simp...
13 Nov 10

Recent Comments

Unknown catalyst version 11.11 and still I have screen flickering, especially with something like banshee....
22 Jan 12 at 12:49:54
Javin @ Java Enum Example Java7 has several feature which developer would love one of them is fork-join framework which allows...
14 Jan 12 at 05:31:40
Javin @ Java Enum Example Java7 has several feature which developer would love one of them is fork-join framework which allows...
14 Jan 12 at 05:27:47
Vijay Hi,
This is the best tutorial I've come across so far to integrate maven with Eclipse even t...
27 Dec 11 at 11:07:13
inebium export vblank_mode=1...
25 Dec 11 at 01:19:14

Categories

All (22)
Android (2)
Java (6)
Linux (14)
Load Testing

Pricing

Sign Up For Free

+420 602 318 949 English / French (GMT+1)

Follow iNebium on twitter Follow us on Twitter

© iNebium 2009-2012 - All rights reserved