postheadericon DES with CBC mode example in Java

DESCBC.java

class DESCBC
{
public KeyGenerator keygenerator;
public SecretKey myDesKey;
Cipher c;
public IvParameterSpec iv;
public DESCBC() throws Exception
{
// Genrate the Key
keygenerator = KeyGenerator.getInstance("DES");
keygenerator.init(new SecureRandom());
myDesKey = keygenerator.generateKey();



// Create the cipher
c = Cipher.getInstance("DES/CBC/PKCS5Padding");

iv = new IvParameterSpec(new byte[8]);
}
public byte[] doEncryption(String s) throws Exception
{
   // Initialize the cipher for encryption
   c.init(Cipher.ENCRYPT_MODE, myDesKey,iv);

   //sensitive information
   byte[] text = s.getBytes();

// Encrypt the text
   byte[] textEncrypted = c.doFinal(text);

return(textEncrypted);
}
public String doDecryption(byte[] s)throws Exception
{

   // Initialize the same cipher for decryption
   c.init(Cipher.DECRYPT_MODE, myDesKey,iv);

   // Decrypt the text
   byte[] textDecrypted = c.doFinal(s);

return(new String(textDecrypted));
}
}



DES.java

import bsr.*;
/*A code from www.bipinrupadiya.com*/
public class DES
{  

public static void main(String[] argv) throws Exception
{
 
DESCBC d=new DESCBC();
byte[] str=d.doEncryption("BipinRupadiya");
System.out.println("Encrypted String : "+str);
System.out.println("Encrypted String : "+d.doDecryption(str));
 
}
}

To execute this code


  • open two command prompt
  • compile bsr package
  • compile DES.java
  • execute DES.java


0 comments:

Blog Archive

Total Pageviews

© BipinRupadiya.com. Powered by Blogger.