1 import lombok.extern.slf4j.Slf4j; 2 import org.apache.commons.codec.binary.Base64; 3 import org.apache.commons.lang3.StringUtils; 4 5 import javax.crypto.Cipher; 6 import javax.crypto.KeyGenerator; 7 import javax.crypto.SecretKey; 8 import java.security.SecureRandom; 9 10 /** 11 * 字符串AES128加密 <加盐> 12 * 13 * @author XuBaofeng. 14 * @date 2018-10-11 18:55. 15 */ 16 @Slf4j 17 public class Aes128Util { 18 19 private static final String KEY_ALGORITHM = "AES"; 20 private static final String SHA1_PRNG = "SHA1PRNG"; 21 /*** 字符编码 ***/ 22 private static final String CHARACTER_CODING = "UTF-8"; 23 /*** 默认的加密算法 ***/ 24 private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding"; 25 /*** 默认的盐 ***/ 26 private static final String DEFAULT_SECRET_KEY = "yanwu0527@163.com"; 27 28 /** 29 * AES 加密操作, 使用默认盐 30 * 31 * @param content 待加密内容 32 * @return 返回Base64转码后的加密数据 33 */ 34 public static String encrypt(String content) { 35 return encrypt(content, DEFAULT_SECRET_KEY); 36 } 37 38 /** 39 * AES 加密操作, 自定义盐 40 * 41 * @param content 待加密内容 42 * @param key 秘钥 43 * @return 返回Base64转码后的加密数据 44 */ 45 public static String encrypt(String content, String key) { 46 if (StringUtils.isBlank(content)) { 47 return content; 48 } 49 if (StringUtils.isBlank(key)) { 50 key = DEFAULT_SECRET_KEY; 51 } 52 try { 53 Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); 54 byte[] byteContent = content.getBytes(CHARACTER_CODING); 55 cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key)); 56 byte[] result = cipher.doFinal(byteContent); 57 return Base64.encodeBase64String(result); 58 } catch (Exception e) { 59 log.error("String: [{}] Aes128Util encryption error.", content, e); 60 } 61 return null; 62 } 63 64 /** 65 * AES 解密操作, 使用默认盐 66 * 67 * @param content 待解密内容 68 * @return 解密数据 69 */ 70 public static String decrypt(String content) { 71 return decrypt(content, DEFAULT_SECRET_KEY); 72 } 73 74 /** 75 * AES 解密操作, 自定义盐 76 * 77 * @param content 待解密内容 78 * @param key 秘钥 79 * @return 解密数据 80 */ 81 public static String decrypt(String content, String key) { 82 if (StringUtils.isBlank(content)) { 83 return content; 84 } 85 if (StringUtils.isBlank(key)) { 86 key = DEFAULT_SECRET_KEY; 87 } 88 try { 89 Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); 90 cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); 91 byte[] result = cipher.doFinal(Base64.decodeBase64(content)); 92 return new String(result, CHARACTER_CODING); 93 } catch (Exception e) { 94 log.error("String: [{}] Aes128Util decryption error.", content, e); 95 } 96 return null; 97 } 98 99 /** 100 * 生成加密秘钥 101 * 102 * @return 103 */ 104 private static SecretKey getSecretKey(String key) throws Exception { 105 SecureRandom secureRandom = SecureRandom.getInstance(SHA1_PRNG); 106 secureRandom.setSeed(key.getBytes()); 107 KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM); 108 kg.init(secureRandom); 109 return kg.generateKey(); 110 } 111 112 }