/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package aesexample;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
/**
*
* @author Whiz
*/
public class AESWithGivenKEy {
public static void main(String[] args) {
try {
String key = "ThiSIsASecretKey";
byte[] ciphertext = encrypt(key, "Hey There");
String x=new BASE64Encoder().encode(ciphertext);
System.out.println("encrypted :"+x);
System.out.println("decrypted value:" + (decrypt(key, ciphertext)));
String key1 = "ThiSIsASEcretKey";
int x123 =323;
byte[] ciphertext1 = encrypt(key1, "Hey There");
String x1=new BASE64Encoder().encode(ciphertext1);
System.out.println("encrypted :"+x1);
System.out.println("decrypted value:" + (decrypt(key1, ciphertext1)));
//
// String key1 = "ThisIsASEcretKey";
// byte[] ciphertext1 = encrypt(key, "HeyThere");
// String xx=new BASE64Encoder().encode(ciphertext1);
// System.out.println("encrypted :"+xx);
// System.out.println("decrypted value:" + (decrypt(key1, ciphertext1)));
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
}
public static byte[] encrypt(String key, String value)
throws GeneralSecurityException {
byte[] raw = key.getBytes(Charset.forName("US-ASCII"));
if (raw.length != 16) {
throw new IllegalArgumentException("Invalid key size.");
}
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec,
new IvParameterSpec(new byte[16]));
return cipher.doFinal(value.getBytes(Charset.forName("US-ASCII")));
}
public static String decrypt(String key, byte[] encrypted)
throws GeneralSecurityException {
byte[] raw = key.getBytes(Charset.forName("US-ASCII"));
if (raw.length != 16) {
throw new IllegalArgumentException("Invalid key size.");
}
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec,
new IvParameterSpec(new byte[16]));
byte[] original = cipher.doFinal(encrypted);
return new String(original, Charset.forName("US-ASCII"));
}
}
No comments:
Post a Comment