java加密解密技术(3)对称加密AES

 

 
  1. import javax.crypto.Cipher;

  2. import javax.crypto.spec.IvParameterSpec;

  3. import javax.crypto.spec.SecretKeySpec;

  4.  
  5. import sun.misc.BASE64Decoder;

  6. import sun.misc.BASE64Encoder;

  7.  
  8. public class AESCoder{

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

  11. SecretKeySpec skeySpec = getKey(strKey);

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

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

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

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

  16.  
  17. return new BASE64Encoder().encode(encrypted);

  18. }

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

  21. SecretKeySpec skeySpec = getKey(strKey);

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

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

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

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

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

  28. String originalString = new String(original);

  29. return originalString;

  30. }

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

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

  34. byte[] arrB = new byte[16]; // 创建一个空的16位字节数组(默认值为0)

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

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

  37. }

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

  39.  
  40. return skeySpec;

  41. }

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

  44. String Code = "中文ABc123";

  45. String key = "1q2w3e4r";

  46. String codE;

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

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

  49. System.out.println("密钥:" + key);

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

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

  52. }

  53. }


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

猜你喜欢

转载自blog.csdn.net/weixin_36058293/article/details/82801009