import lombok.extern.slf4j.Slf4j; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Base64; @Slf4j public class AESService { private final String key ;//密钥key private final String iv ;//向量iv public AESService(String key, String iv) { this.key = key; this.iv = iv; } //加密 public byte[] encrypt(byte[] content){ try{ byte[] raw = key.getBytes(StandardCharsets.UTF_8); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式" //使用CBC模式,需要一个向量iv,可增加加密算法的强度 IvParameterSpec ips = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ips); byte[] encrypted = cipher.doFinal(content); return encrypted; }catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidAlgorithmParameterException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex){ log.error("加密出现错误",ex); } return null; } //解密 public byte[] decrypt(byte[] content) { try { byte[] raw = key.getBytes(StandardCharsets.UTF_8); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec ips = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, skeySpec, ips); return cipher.doFinal(content); } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException ex) { log.error("解密错误", ex); } return null; } }
aes加密
最新推荐文章于 2024-07-12 15:51:39 发布