AES加解密工具类AESUtil记录

1、首先引入需要的jar包,如下所示:

1 <dependency>
2     <groupId>commons-codec</groupId>
3     <artifactId>commons-codec</artifactId>
4     <version>1.10</version>
5 </dependency>

2、完整的加密,解密代码,如下所示:

  1 package com.bie.utils;
  2 
  3 import org.apache.commons.codec.binary.Base64;
  4 
  5 import javax.crypto.Cipher;
  6 import javax.crypto.KeyGenerator;
  7 import javax.crypto.SecretKey;
  8 import javax.crypto.spec.SecretKeySpec;
  9 import java.security.NoSuchAlgorithmException;
 10 import java.security.SecureRandom;
 11 import java.util.UUID;
 12 import java.util.logging.Level;
 13 import java.util.logging.Logger;
 14 
 15 /**
 16  * 
 17  * @author biehl
 18  *
 19  */
 20 public class AESUtil {
 21 
 22     private static final String KEY_ALGORITHM = "AES";
 23     private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
 24 
 25     // appKey,每隔一段时间进行替换即可
 26     // 可以设计成保存到数据库中或者那里,然后进行每隔一段时间进行替换,增加保密的安全性
 27     private static final String appKey = "fa8f92af-fa83-443a-9626-e32b64481320";
 28 
 29     /**
 30      * AES 加密操作
 31      *
 32      * @param content
 33      *            待加密内容
 34      * @param appKey
 35      *            加密appKey
 36      * @return 返回Base64转码后的加密数据
 37      */
 38     public static String encrypt(String content, String appKey) {
 39         try {
 40             Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
 41 
 42             byte[] byteContent = content.getBytes("utf-8");
 43 
 44             cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(appKey));// 初始化为加密模式的密码器
 45 
 46             byte[] result = cipher.doFinal(byteContent);// 加密
 47 
 48             return Base64.encodeBase64String(result);// 通过Base64转码返回
 49         } catch (Exception ex) {
 50             ex.printStackTrace();
 51         }
 52         return null;
 53     }
 54 
 55     /**
 56      * AES 解密操作
 57      * 
 58      * @param content
 59      *            待解密内容
 60      * @param appKey
 61      *            加密appKey
 62      * @return
 63      */
 64     public static String decrypt(String content, String appKey) {
 65 
 66         try {
 67             // 实例化
 68             Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
 69 
 70             // 使用密钥初始化,设置为解密模式
 71             cipher.init(Cipher.DECRYPT_MODE, getSecretKey(appKey));
 72 
 73             // 执行操作
 74             byte[] result = cipher.doFinal(Base64.decodeBase64(content));
 75 
 76             return new String(result, "utf-8");
 77         } catch (Exception ex) {
 78             Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
 79         }
 80 
 81         return null;
 82     }
 83 
 84     /**
 85      * 生成加密秘钥
 86      *
 87      * @return
 88      */
 89     private static SecretKeySpec getSecretKey(String appKey) {
 90         // 返回生成指定算法密钥生成器的 KeyGenerator 对象
 91         KeyGenerator kg = null;
 92 
 93         try {
 94             kg = KeyGenerator.getInstance(KEY_ALGORITHM);
 95 
 96             // SecureRandom 实现随操作系统本身的內部状态,除非调用方在调用 getInstance 方法之后又调用了 setSeed 方法;该实现在
 97             // windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系统上则不同。解决在linux操作系统中加密产生的字符串不一致问题。
 98             SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
 99 
100             secureRandom.setSeed(appKey.getBytes());
101 
102             // AES 要求密钥长度为 128
103             kg.init(128, secureRandom);
104 
105             // 生成一个密钥
106             SecretKey secretKey = kg.generateKey();
107 
108             return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
109         } catch (NoSuchAlgorithmException ex) {
110             ex.printStackTrace();
111         }
112 
113         return null;
114     }
115 
116     public static void main(String[] args) {
117         // for (int i = 0; i < 10; i++) {
118         // String userNo = "410725666659845865" + i;
119         // System.out.println("未加密的身份证号码userNo: " + userNo);
120         // String s1 = AESUtil.encrypt(userNo, AESUtil.appKey);
121         // System.out.println("加密的身份证号码userNo: " + s1);
122         // }
123 
124         String userNo = "410725666659845865";
125         System.out.println("未加密的身份证号码userNo: " + userNo);
126         String encryptUserNo = AESUtil.encrypt(userNo, AESUtil.appKey);
127         System.out.println("加密的身份证号码userNo: " + encryptUserNo);
128         System.out.println("加密的身份证号码userNo: " + AESUtil.encrypt(userNo, AESUtil.appKey));
129 
130         String decryptUserNo = AESUtil.decrypt(encryptUserNo, AESUtil.appKey);
131         System.out.println("解密的身份证号码userNo: " + decryptUserNo);
132 
133         System.out.println(UUID.randomUUID().toString());
134 
135         //
136         // // 直接使用AESUtil类调用静态方法decrypt,将加密的身份证号码、密钥appKey传进去即可。
137         // String decryptUserNo = AESUtil.decrypt(s1, appKey);
138         // System.out.println("解密的身份证号码userNo:" + decryptUserNo);
139     }
140 
141 }

运行效果,如下所示:

1 未加密的身份证号码userNo: 410725666659845865
2 加密的身份证号码userNo: q6zDC7F3hBuFXNT3wTOWmeZuW66xVtbaI0sgqUcuedg=
3 加密的身份证号码userNo: q6zDC7F3hBuFXNT3wTOWmeZuW66xVtbaI0sgqUcuedg=
4 解密的身份证号码userNo: 410725666659845865
5 5c8935c2-76e7-4955-974e-bf6450342c23
6 
7 Process finished with exit code 0

 

posted on 2020-09-10 10:34  别先生  阅读(1183)  评论(0编辑  收藏  举报