Showing posts with label DES algorithm. Show all posts
Showing posts with label DES algorithm. Show all posts

Tuesday, May 3, 2011

DES algorithm

DES algorithm is well explained by J. Orlin Grabbe in his article.
Follow http://www.orlingrabbe.com/des.htm

DES implementation

Source code Language : Java
Crypto Packages are used

-------------------------------------------------------------------------------------------------------------


/**
 * implement DES algorithm
 * @author chakreshprasad
 */

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class des
{
Cipher ecipher;
Cipher dcipher;
KeySpec keysp;
SecretKeyFactory keyf;
byte keyasbyte[];
String enkey;
Cipher cipher;
SecretKey skey;
des() throws Exception
{
    enkey="hi.i.am.chakresh";
    keyasbyte=enkey.getBytes("UTF8");                 //utf8 is unicode format
    keysp=new DESKeySpec(keyasbyte);
    keyf=SecretKeyFactory.getInstance("DES");     //DES is encryption scheme
    cipher=Cipher.getInstance("DES");
    skey=keyf.generateSecret(keysp);
}

/*Encrypt a string*/

public String encrypt(String plain) throws Exception
{
    String enstring="";
    cipher.init(Cipher.ENCRYPT_MODE, skey);
    byte[] plaintext=plain.getBytes("UTF8");
    byte[] encrytext=cipher.doFinal(plaintext);
    BASE64Encoder base64en=new BASE64Encoder();
    enstring=base64en.encode(encrytext);
    return enstring;
}

/*Decrypt a string */

public String decrypt(String enstring)throws Exception
{
    String destring="";
    cipher.init(Cipher.DECRYPT_MODE, skey);
    BASE64Decoder base64de=new BASE64Decoder();
    byte[] enctext=base64de.decodeBuffer(enstring);
    byte plain[]=cipher.doFinal(enctext);
    destring=byte2string(plain);
    return destring;  
}
public String byte2string(byte plain[])
{
    StringBuffer str=new StringBuffer();
    for(int i=0;i<plain.length;i++)
        str.append((char)plain[i]);
    return str.toString();
}
    public static void main(String[] args) throws Exception
    {

       /*Generate an encrypter*/

       des ds=new des();
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       String plain="",ciphertext="";
       System.out.println("Enter plain text : ");
       plain=br.readLine();
       ciphertext=ds.encrypt(plain);
       System.out.println("\nCipher text: "+ciphertext);
       plain=ds.decrypt(ciphertext);
       System.out.println("\nPlain text: "+plain);
      
    }

}

--------------------------------------------------------------------------------
Output:


Enter plain text :
chakreshprasad mahajan

Cipher text: qYv2ruDW4Fn8i+tTzdyCab5I3RvWxfw+

Plain text: chakreshprasad mahajan