AES加密与解密(秘钥)

转载地址:https://blog.csdn.net/lichuangcsdn/article/details/80842338

 

  1 package com.snsoft.modules.biz.test;
  2 
  3 import org.slf4j.Logger;
  4 import org.slf4j.LoggerFactory;
  5 import sun.misc.BASE64Decoder;
  6 import sun.misc.BASE64Encoder;
  7 import tk.mybatis.mapper.util.StringUtil;
  8 
  9 import javax.crypto.Cipher;
 10 import javax.crypto.KeyGenerator;
 11 import javax.crypto.SecretKey;
 12 import javax.crypto.spec.SecretKeySpec;
 13 import java.io.IOException;
 14 import java.security.SecureRandom;
 15 
 16 /**
 17  * AES加密解密
 18  *
 19  * @author lichuang
 20  * @since 2018-03-23
 21  */
 22 public class SecurityUtil {
 23 
 24     private static final Logger logger = LoggerFactory.getLogger(SecurityUtil.class);
 25 
 26     private static final String ENCODING = "UTF-8";
 27 
 28     private static final String PASSWORD = "46EBA22EF5204DD5B110A1F730513965"; // 加密秘钥
 29 
 30     /**
 31      * AES加密
 32      *
 33      * @param content
 34      *            明文
 35      * @return 密文
 36      */
 37     public static String encryptAES(String content) {
 38         if (StringUtil.isEmpty(content)) {
 39             throw new RuntimeException("明文不能为空!");
 40         }
 41         byte[] encryptResult = encrypt(content, PASSWORD);
 42         String encryptResultStr = parseByte2HexStr(encryptResult);
 43         // BASE64位加密
 44         encryptResultStr = ebotongEncrypto(encryptResultStr);
 45         return encryptResultStr;
 46     }
 47 
 48     /**
 49      * AES解密
 50      *
 51      * @param encryptResultStr
 52      *            密文
 53      * @return 明文
 54      */
 55     public static String decryptAES(String encryptResultStr) {
 56         if (StringUtil.isEmpty(encryptResultStr)) {
 57             throw new RuntimeException("密文不能为空");
 58         }
 59         // BASE64位解密
 60         try {
 61             String decrpt = ebotongDecrypto(encryptResultStr);
 62             byte[] decryptFrom = parseHexStr2Byte(decrpt);
 63             byte[] decryptResult = decrypt(decryptFrom, PASSWORD);
 64             return new String(decryptResult);
 65         } catch (Exception e) { // 当密文不规范时会报错,可忽略,但调用的地方需要考虑
 66             return null;
 67         }
 68     }
 69 
 70     /**
 71      * 加密字符串
 72      */
 73     private static String ebotongEncrypto(String str) {
 74         BASE64Encoder base64encoder = new BASE64Encoder();
 75         String result = str;
 76         if (str != null && str.length() > 0) {
 77             try {
 78                 byte[] encodeByte = str.getBytes(ENCODING);
 79                 result = base64encoder.encode(encodeByte);
 80             } catch (Exception e) {
 81                 e.printStackTrace();
 82             }
 83         }
 84         // base64加密超过一定长度会自动换行 需要去除换行符
 85         return result.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");
 86     }
 87 
 88     /**
 89      * 解密字符串
 90      */
 91     private static String ebotongDecrypto(String str) {
 92         BASE64Decoder base64decoder = new BASE64Decoder();
 93         try {
 94             byte[] encodeByte = base64decoder.decodeBuffer(str);
 95             return new String(encodeByte);
 96         } catch (IOException e) {
 97             logger.error("IO 异常",e);
 98             return str;
 99         }
100     }
101 
102     /**
103      * 加密
104      *
105      * @param content
106      *            需要加密的内容
107      * @param password
108      *            加密密码
109      * @return
110      */
111     private static byte[] encrypt(String content, String password) {
112         try {
113             KeyGenerator kgen = KeyGenerator.getInstance("AES");
114             // 注意这句是关键,防止linux下 随机生成key。用其他方式在Windows上正常,但Linux上会有问题
115             SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
116             secureRandom.setSeed(password.getBytes());
117             kgen.init(128, secureRandom);
118             // kgen.init(128, new SecureRandom(password.getBytes()));
119             SecretKey secretKey = kgen.generateKey();
120             byte[] enCodeFormat = secretKey.getEncoded();
121             SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
122             Cipher cipher = Cipher.getInstance("AES");// 创建密码器
123             byte[] byteContent = content.getBytes("utf-8");
124             cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
125             byte[] result = cipher.doFinal(byteContent);
126             return result; // 加密
127         } catch (Exception e) {
128             logger.error("加密异常", e);
129         }
130         return null;
131     }
132 
133     /**
134      * 解密
135      *
136      * @param content
137      *            待解密内容
138      * @param password
139      *            解密密钥
140      * @return
141      */
142     private static byte[] decrypt(byte[] content, String password) {
143         try {
144             KeyGenerator kgen = KeyGenerator.getInstance("AES");
145             // 防止linux下 随机生成key
146             SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
147             secureRandom.setSeed(password.getBytes());
148             kgen.init(128, secureRandom);
149             // kgen.init(128, new SecureRandom(password.getBytes()));
150             SecretKey secretKey = kgen.generateKey();
151             byte[] enCodeFormat = secretKey.getEncoded();
152             SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
153             Cipher cipher = Cipher.getInstance("AES");// 创建密码器
154             cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
155             byte[] result = cipher.doFinal(content);
156             return result; // 加密
157         } catch (Exception e) {
158             logger.error("解密异常", e);
159         }
160         return null;
161     }
162 
163     /**
164      * 将二进制转换成16进制
165      *
166      * @param buf
167      * @return
168      */
169     private static String parseByte2HexStr(byte buf[]) {
170         StringBuffer sb = new StringBuffer();
171         for (int i = 0; i < buf.length; i++) {
172             String hex = Integer.toHexString(buf[i] & 0xFF);
173             if (hex.length() == 1) {
174                 hex = '0' + hex;
175             }
176             sb.append(hex.toUpperCase());
177         }
178         return sb.toString();
179     }
180 
181     /**
182      * 将16进制转换为二进制
183      *
184      * @param hexStr
185      * @return
186      */
187     private static byte[] parseHexStr2Byte(String hexStr) {
188         if (hexStr.length() < 1)
189             return null;
190         byte[] result = new byte[hexStr.length() / 2];
191         for (int i = 0; i < hexStr.length() / 2; i++) {
192             int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
193             int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
194             result[i] = (byte) (high * 16 + low);
195         }
196         return result;
197     }
198 
199     public static void main(String[] args) {
200         express();
201     }
202 
203     /**
204      * 测试
205      */
206     private static void express() {
207         System.out.println("加密解密试试:");
208         String content = "你好北京";
209         System.out.println("原内容为:" + content);
210         String encryContent = encryptAES(content);
211         System.out.println("加密后的内容为:" + encryContent);
212         String decryContent = decryptAES(encryContent);
213         System.out.println("解密后的内容为:" + decryContent);
214     }
215 
216 }

 

转载于:https://www.cnblogs.com/lidar/p/11558450.html

你可能感兴趣的:(AES加密与解密(秘钥))