AESUtil加密工具
1 package com.example.tempshiro.util; 2 3 import lombok.extern.slf4j.Slf4j; 4 import org.apache.commons.codec.binary.Base64; 5 6 import javax.crypto.Cipher; 7 import javax.crypto.IllegalBlockSizeException; 8 import javax.crypto.NoSuchPaddingException; 9 import javax.crypto.spec.IvParameterSpec; 10 import javax.crypto.spec.SecretKeySpec; 11 import java.security.NoSuchAlgorithmException; 12 13 @Slf4j 14 public class AESUtil { 15 16 // 默认算法 17 private static final String ALGORITHM_STR = "AES/CBC/PKCS5Padding"; 18 19 20 public AESUtil() { 21 } 22 23 /** 24 * @Description: aes加密 25 * @Params: [content, encryptKey] 26 * @Return: java.lang.String 27 */ 28 public static String aesEncode(String content,String encryptKey){ 29 SecretKeySpec keySpec = new SecretKeySpec(encryptKey.getBytes(),"AES"); 30 31 try { 32 Cipher cipher = Cipher.getInstance(ALGORITHM_STR); 33 cipher.init(Cipher.ENCRYPT_MODE,keySpec,new IvParameterSpec(encryptKey.getBytes())); 34 byte[] byteEncode = content.getBytes("utf-8"); 35 byte[] byteAES = cipher.doFinal(byteEncode); 36 return new String(Base64.encodeBase64(byteAES)); 37 } catch (Exception e) { 38 log.error("密文加密失败"+e.getMessage(),e); 39 throw new RuntimeException("密文加密失败"); 40 } 41 } 42 43 public static String aesDecode(String content, String decryptKey) { 44 try { 45 SecretKeySpec keySpec = new SecretKeySpec(decryptKey.getBytes("utf-8"), "AES"); 46 47 //根据指定算法AES自成密码器 48 Cipher cipher = Cipher.getInstance(ALGORITHM_STR); 49 //初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY 50 cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(decryptKey.getBytes("utf-8"))); 51 //8.将加密并编码base64后的字符串内容base64解码成字节数组 52 byte[] bytesContent = Base64.decodeBase64(content); 53 /* 54 * 解密 55 */ 56 byte[] byteDecode = cipher.doFinal(bytesContent); 57 return new String(byteDecode, "utf-8"); 58 } catch (NoSuchAlgorithmException e) { 59 log.error("没有指定的加密算法::"+e.getMessage(),e); 60 } catch (IllegalBlockSizeException e) { 61 log.error("非法的块大小"+"::"+e.getMessage(),e); 62 throw new RuntimeException("密文解密失败"); 63 //e.printStackTrace(); 64 } catch (NullPointerException e) { 65 log.error("秘钥解析空指针异常"+"::"+e.getMessage(),e); 66 throw new RuntimeException("秘钥解析空指针异常"); 67 } catch (Exception e) { 68 log.error("秘钥AES解析出现未知错误"+"::"+e.getMessage(),e); 69 throw new RuntimeException("密文解密失败"); 70 } 71 //如果有错就返null 72 return null; 73 74 } 75 }