13
Nov/10
Follow iNebium on twitter

3DES Encryption in Java and DES Encryption in Java

[13 Nov 10 at 09:23:26 - 7 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

7 Comment(s)

inebium  -  05 Mar 2012 at 15:22:42
down  up
it's not a method, it's the constructor of the class

Anonymous  -  05 Mar 2012 at 14:28:05
down  up
method Encrypter has no return type .... ?

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 create a self signed certificate?
You need a self signed certificate for your website over https, this post is here to take you throug...
26 Apr 12
To not increase PCM value when increasing volume with pulseaudio
When you use pulseaudio and you increase the volume, it will increase the front volume but also the ...
17 Apr 12
Skype: fix crackling sound
If skype on linux gives you crackling sound and you use pulseaudio, here is the solution to fix it. ...
17 Apr 12
Install grub when booting from live CD or usb
You need to re-install grub on your drive when booting from usb or live CD. This post is made for yo...
12 Apr 12
Git: common and useful commands
I use git and literally love it but I have one problem with it, I often forget how to do things mean...
22 Mar 12

Recent Comments

vvy2000 ubuntu need root for executing this procedure.
sudo -s to get root privileges. ...
04 May 12 at 09:40:53
Danilo Cesar echo 3 | sudo tee /proc/sys/vm/drop_caches ...
16 Mar 12 at 09:32:42
inebium it's not a method, it's the constructor of the class...
05 Mar 12 at 03:22:42
Unknown method Encrypter has no return type .... ? ...
05 Mar 12 at 02:28:05
Unknown catalyst version 11.11 and still I have screen flickering, especially with something like banshee....
22 Jan 12 at 12:49:54

Categories

All (27)
Android (2)
Java (6)
Linux (18)
Misc (1)
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