import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES
{
static String IV = "AAAAAAAAAAAAAAAA";
static String plaintext = "test text 123\0\0\0"; //因為AES需要16字元,在這邊要把欲加密字串加至16字元
static byte[] keys;
public static void main(String [] args)
{
try
{
System.out.println("===AES範例===");
System.out.println("plain: " + plaintext);
byte[] cipher = encrypt(plaintext);
System.out.print("cipher: ");
for (int i=0; i<cipher.length; i++)
System.out.print(new Integer(cipher[i])+" ");
System.out.println("");
String decrypted = decrypt(cipher);
System.out.println("decrypt: " + decrypted);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static byte[] encrypt(String plainText) throws Exception //加密
{
KeyGenerator keyG = KeyGenerator.getInstance("AES");
keyG.init(128);
SecretKey secuK = keyG.generateKey(); //取得KEY
keys = secuK.getEncoded();
String str=new String(keys, "iso-8859-1");;
System.out.print("Key: ");
for (int i=0; i<keys.length; i++)
System.out.print(new Integer(keys[i])+" ");
System.out.println();
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(keys, "AES");
cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
return cipher.doFinal(plainText.getBytes("UTF-8"));
}
public static String decrypt(byte[] cipherText) throws Exception //解密
{
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(keys, "AES");
cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
return new String(cipher.doFinal(cipherText),"UTF-8");
}
}
執行結果
如果您喜歡我的文章,請在文章最末按5下Like!
我將得到LikeCoin的回饋:)
回饋由LikeCoin基金會出資,您只要註冊/登入帳號(FB、Google帳號都可以註冊,流程超快),按L五次左鍵,可以贊助我的文章且完全不會花到錢!
支持創作,正向交流:)
沒有留言:
張貼留言