postheadericon 3DES with CBC mode example in Java

D3ESCBC.java

package bsr;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
class D3ESCBC
{
public KeyGenerator keygenerator;
public SecretKey myDesKey;
Cipher c;
public IvParameterSpec iv;
public D3ESCBC() throws Exception
{


               // Genrate the Key
keygenerator = KeyGenerator.getInstance("DESede");
keygenerator.init(new SecureRandom());
myDesKey = keygenerator.generateKey();

// Create the cipher
c = Cipher.getInstance("DESede/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));
}
}



D3ES.java

import bsr.*;
public class D3ES
{  

public static void main(String[] argv) throws Exception
{
 
D3ESCBC d=new D3ESCBC();

String 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 D3ES.java
  • execute D3ES.java

3 comments:

張志宏 said...

thank you very much! Help me understand M3ES a lot.

Leandro S. said...

String str=d.doEncryption("BipinRupadiya");;

Besides the two ;

Yo don't have any method that recieve String and returns String.

The same here:

System.out.println("Encrypted String : "+d.doDecryption(str));

kavithasathish said...

Thanks for posting this information it really useful for everyone.
French Classes in Chennai
french courses in chennai
Spoken English Classes in Chennai
TOEFL Coaching in Chennai
pearson vue test center in chennai
German Language Course in Chennai
French Classes in T Nagar
French Classes in Anna Nagar

Follow by Email

Blog Archive

Total Pageviews

© BipinRupadiya.com. Powered by Blogger.