Implementing DES Algorithm
Code :import javax.crypto.*;
import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.spec.*;
import javax.crypto.spec.IvParameterSpec;
import java.lang.*;
public class DES
{
Cipher ecipher;
Cipher dcipher;
DES(SecretKey key)
{
try
{
ecipher=Cipher.getInstance("DES");
dcipher=Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
catch(javax.crypto.NoSuchPaddingException e) {}
catch(java.security.NoSuchAlgorithmException e) {}
catch(java.security.InvalidKeyException e) {}
}
public String encrypt(String str)
{
try
{
byte[] utf8=str.getBytes("UTF8");
byte[] enc=ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc); }
catch(javax.crypto.BadPaddingException e) {}
catch(IllegalBlockSizeException e) {}
catch(UnsupportedEncodingException e) {}
catch(java.io.IOException e) {}
return null; }
public String decrypt(String str)
{
try {
byte[] dec=new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8=dcipher.doFinal(dec);
return new String(utf8, "UTF8"); }
catch(javax.crypto.BadPaddingException e) {}
catch(IllegalBlockSizeException e) {}
catch(UnsupportedEncodingException e) {}
catch(java.io.IOException e) {}
return null; }
public static void main(String[] args)
{
System.out.println();
System.out.println("Encrypting String Using DES");
try
{
SecretKey key=KeyGenerator.getInstance("DES").generateKey();
DES d=new DES(key);
String s="Dont tell anybody";
String encrypted=d.encrypt(s);
String decrypted=d.decrypt(encrypted);
System.out.println("Original String is:"+s);
System.out.println("Encrpypted String is:"+encrypted);
System.out.println("Decrypted String is:"+decrypted);
}catch(Exception e) {}
} }
If the answers is incorrect or not given, you can answer the above question in the comment box. If the answers is incorrect or not given, you can answer the above question in the comment box.