1. 程式人生 > >java加密解密技術(3)對稱加密AES

java加密解密技術(3)對稱加密AES

  1. import javax.crypto.Cipher;

  2. import javax.crypto.spec.IvParameterSpec;

  3. import javax.crypto.spec.SecretKeySpec;

  4. import sun.misc.BASE64Decoder;

  5. import sun.misc.BASE64Encoder;

  6. public class AESCoder{

  7. public static String encrypt(String strKey, String strIn) throws Exception {

  8. SecretKeySpec skeySpec = getKey(strKey);

  9. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

  10. IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());

  11. cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

  12. byte[] encrypted = cipher.doFinal(strIn.getBytes());

  13. return new BASE64Encoder().encode(encrypted);

  14. }

  15. public static String decrypt(String strKey, String strIn) throws Exception {

  16. SecretKeySpec skeySpec = getKey(strKey);

  17. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

  18. IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());

  19. cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

  20. byte[] encrypted1 = new BASE64Decoder().decodeBuffer(strIn);

  21. byte[] original = cipher.doFinal(encrypted1);

  22. String originalString = new String(original);

  23. return originalString;

  24. }

  25. private static SecretKeySpec getKey(String strKey) throws Exception {

  26. byte[] arrBTmp = strKey.getBytes();

  27. byte[] arrB = new byte[16]; // 建立一個空的16位位元組陣列(預設值為0)

  28. for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {

  29. arrB[i] = arrBTmp[i];

  30. }

  31. SecretKeySpec skeySpec = new SecretKeySpec(arrB, "AES");

  32. return skeySpec;

  33. }

  34. public static void main(String[] args) throws Exception {

  35. String Code = "中文ABc123";

  36. String key = "1q2w3e4r";

  37. String codE;

  38. codE = AESCoder.encrypt(key, Code);

  39. System.out.println("原文:" + Code);

  40. System.out.println("金鑰:" + key);

  41. System.out.println("密文:" + codE);

  42. System.out.println("解密:" + AESCoder.decrypt(key, codE));

  43. }

  44. }

轉自 http://www.cnblogs.com/freeliver54/archive/2011/10/09/2203342.html