You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

AES.java 8.4 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import java.io.IOException;
  2. import java.io.UnsupportedEncodingException;
  3. import java.io.File;
  4. import java.io.InputStreamReader;
  5. import java.io.BufferedReader;
  6. import java.io.BufferedWriter;
  7. import java.io.FileInputStream;
  8. import java.io.FileWriter;
  9. import java.nio.charset.Charset;
  10. import java.security.InvalidKeyException;
  11. import java.security.NoSuchAlgorithmException;
  12. import java.security.SecureRandom;
  13. import java.util.Base64;
  14. import java.util.Scanner;
  15. import java.util.Arrays;
  16. import javax.crypto.BadPaddingException;
  17. import javax.crypto.Cipher;
  18. import javax.crypto.IllegalBlockSizeException;
  19. import javax.crypto.KeyGenerator;
  20. import javax.crypto.NoSuchPaddingException;
  21. import javax.crypto.SecretKey;
  22. import javax.crypto.spec.SecretKeySpec;
  23. //import sun.misc.BASE64Decoder;
  24. //import sun.misc.BASE64Encoder;
  25. //import RC4;
  26. public class AES {
  27. public static String bytesToHexString(byte[] src) {
  28. StringBuilder stringBuilder = new StringBuilder("");
  29. if (src == null || src.length <= 0) {
  30. return null;
  31. }
  32. for (int i = 0; i < src.length; i++) {
  33. int v = src[i] & 0xFF;
  34. String hv = Integer.toHexString(v);
  35. if (hv.length() < 2) {
  36. stringBuilder.append(0);
  37. }
  38. stringBuilder.append(hv);
  39. }
  40. return stringBuilder.toString();
  41. }
  42. public static byte[] hexStringToBytes(String hexString) {
  43. if (hexString == null || hexString.equals("")) {
  44. return null;
  45. }
  46. hexString = hexString.toUpperCase();
  47. int length = hexString.length() / 2;
  48. char[] hexChars = hexString.toCharArray();
  49. byte[] d = new byte[length];
  50. for (int i = 0; i < length; i++) {
  51. int pos = i * 2;
  52. d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
  53. }
  54. return d;
  55. }
  56. private static byte charToByte(char c) {
  57. return (byte) "0123456789ABCDEF".indexOf(c);
  58. }
  59. public static String AES_Encode(String encodeRules, String content) {
  60. try {
  61. // 1.构造密钥生成器,指定为AES算法,不区分大小写
  62. KeyGenerator keygen = KeyGenerator.getInstance("AES");
  63. // 2.根据ecnodeRules规则初始化密钥生成器
  64. // 生成一个128位的随机源,根据传入的字节数组
  65. // keygen.init(128, new SecureRandom(encodeRules.getBytes()));
  66. SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
  67. secureRandom.setSeed(encodeRules.getBytes());
  68. keygen.init(128, secureRandom);
  69. // 3.产生原始对称密钥
  70. SecretKey original_key = keygen.generateKey();
  71. // 4.获得原始对称密钥的字节数组
  72. byte[] raw = original_key.getEncoded();
  73. // 5.根据字节数组生成AES密钥
  74. SecretKey key = new SecretKeySpec(raw, "AES");
  75. // 6.根据指定算法AES自成密码器
  76. Cipher cipher = Cipher.getInstance("AES");
  77. // 7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
  78. cipher.init(Cipher.ENCRYPT_MODE, key);
  79. // 8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
  80. byte[] byte_encode = content.getBytes("utf-8");
  81. // 9.根据密码器的初始化方式--加密:将数据加密
  82. byte[] byte_AES = cipher.doFinal(byte_encode);
  83. // 10.将加密后的数据转换为字符串
  84. // 这里用Base64Encoder中会找不到包
  85. // 解决办法:
  86. // 在项目的Build path中先移除JRE System Library,再添加库JRE System Library,重新编译后就一切正常了。
  87. // String AES_encode=new String(new BASE64Encoder().encode(byte_AES));
  88. String AES_encode = new String(bytesToHexString(byte_AES));
  89. // 11.将字符串返回
  90. return AES_encode;
  91. } catch (NoSuchAlgorithmException e) {
  92. e.printStackTrace();
  93. } catch (NoSuchPaddingException e) {
  94. e.printStackTrace();
  95. } catch (InvalidKeyException e) {
  96. e.printStackTrace();
  97. } catch (IllegalBlockSizeException e) {
  98. e.printStackTrace();
  99. } catch (BadPaddingException e) {
  100. e.printStackTrace();
  101. } catch (UnsupportedEncodingException e) {
  102. e.printStackTrace();
  103. }
  104. // 如果有错就返加nulll
  105. return null;
  106. }
  107. /*
  108. * 解密
  109. * 解密过程:
  110. * 1.同加密1-4步
  111. * 2.将加密后的字符串反纺成byte[]数组
  112. * 3.将加密内容解密
  113. */
  114. public static String AES_Decode(String encodeRules, String content) {
  115. String ss;
  116. try {
  117. // 1.构造密钥生成器,指定为AES算法,不区分大小写
  118. KeyGenerator keygen = KeyGenerator.getInstance("AES");
  119. // 2.根据ecnodeRules规则初始化密钥生成器
  120. // 生成一个128位的随机源,根据传入的字节数组
  121. // keygen.init(128, new SecureRandom(encodeRules.getBytes()));
  122. SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
  123. secureRandom.setSeed(encodeRules.getBytes());
  124. keygen.init(128, secureRandom);
  125. // 3.产生原始对称密钥
  126. SecretKey original_key = keygen.generateKey();
  127. // 4.获得原始对称密钥的字节数组
  128. byte[] raw = original_key.getEncoded();
  129. // 5.根据字节数组生成AES密钥
  130. SecretKey key = new SecretKeySpec(raw, "AES");
  131. // 6.根据指定算法AES自成密码器
  132. Cipher cipher = Cipher.getInstance("AES");
  133. // 7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY
  134. cipher.init(Cipher.DECRYPT_MODE, key);
  135. // 8.将加密并编码后的内容解码成字节数组
  136. byte[] byte_content = hexStringToBytes(content);
  137. // byte [] byte_content= new BASE64Decoder().decodeBuffer(content);
  138. // System.out.println("ttttttttttttttttttttttttttt");
  139. // System.out.println(new String(byte_content, "UTF-8"));
  140. /*
  141. * 解密
  142. */
  143. byte[] byte_decode = cipher.doFinal(byte_content);
  144. String AES_decode = new String(byte_decode, "utf-8");
  145. return AES_decode;
  146. } catch (NoSuchAlgorithmException e) {
  147. ss = "NoSuchAlgorithmException";
  148. e.printStackTrace();
  149. } catch (NoSuchPaddingException e) {
  150. ss = "NoSuchPaddingException";
  151. e.printStackTrace();
  152. } catch (InvalidKeyException e) {
  153. ss = "InvalidKeyException";
  154. e.printStackTrace();
  155. } catch (IOException e) {
  156. ss = "IOException";
  157. e.printStackTrace();
  158. } catch (IllegalBlockSizeException e) {
  159. ss = "IllegalBlockSizeException";
  160. e.printStackTrace();
  161. } catch (BadPaddingException e) {
  162. ss = "BadPaddingException";
  163. e.printStackTrace();
  164. }
  165. // 如果有错就返加nulll
  166. return ss;
  167. }
  168. public static void main(String[] args) {
  169. // MyClass se=new MyClass();
  170. // Scanner scanner=new Scanner(System.in);
  171. /*
  172. * 加密
  173. */
  174. System.out.println("使用AES对称加密,请输入加密的规则");
  175. // String encodeRules=scanner.next();
  176. System.out.println("请输入要加密的内容:");
  177. String encodeRules = "a02254eb247146dfa446c4b2795ebf90";
  178. String content = "32770";
  179. String outstr = AES_Encode(encodeRules, content);
  180. System.out.println("根据输入的规则" + encodeRules + "加密后的密文是:" + outstr);
  181. /*
  182. * 解密
  183. */
  184. System.out.println("使用AES对称解密,请输入加密的规则:(须与加密相同)");
  185. String byte_str = "0212f41b372fe457c3f7df0757151615";
  186. outstr = AES_Decode(encodeRules, byte_str);
  187. System.out.println("根据输入的规则" + encodeRules + "解密后的明文是:" + outstr);
  188. }
  189. }