Cryptography using Java, Encryption/ Decryption using java with a well-known algorithm Advanced Encryption Standard (AES) 128bit or 16-byte key.
package Cryptography;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class EncDecAES
{
private static final String ALGO="AES";
public static void main(String[] args) throws Exception
{
String sKey="ASDF1234ASDF1234"; // 16 byte or 128 bit key value
Key key =new SecretKeySpec(sKey.getBytes(), ALGO);
String pt="Coding Adda Blog is only for education purpose.";
System.out.println(" Plain text are: "+pt);
String ct= encrypt(pt, key);
System.out.println(" Cipher text are: "+ct);
String dt= decrypt(ct, key);
System.out.println(" decrypted text are: "+dt);
}
public static String encrypt(String ct, Key key) throws Exception
{
Cipher c= Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal= c.doFinal(ct.getBytes());
String encString = new BASE64Encoder().encode(encVal);
return encString;
}
public static String decrypt(String pt, Key key) throws Exception
{
Cipher c= Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decodeVal=new BASE64Decoder().decodeBuffer(pt);
byte[] decVal= c.doFinal(decodeVal);
String decString= new String(decVal);
return decString;
}
}
Output:-
No comments:
Post a Comment