专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

Java-AES加密解密


import java.io.UnsupportedEncodingException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.UUID; 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; public class AesUtil { private final static String AES = "AES"; private final static String UTF8 = "UTF-8"; //定义一个16byte的初始向量 private static final String IV_STRING = "12345678abcdefgh"; /** * 产生一个16位的密钥字符串 * [@return](https://my.oschina.net/u/556800) */ public static String generateSecreKey() { String uuid = UUID.randomUUID().toString(); uuid = uuid.replaceAll("-", ""); return uuid.substring(0, 16); } public static String aesEncry(String content,String key) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { byte[] contentByte = content.getBytes(UTF8); byte[] keyByte = key.getBytes(); //初始化一个密钥对象 SecretKeySpec keySpec = new SecretKeySpec(keyByte ,AES); //初始化一个初始向量,不传入的话,则默认用全0的初始向量 byte[] initParam = IV_STRING.getBytes(); IvParameterSpec ivSpec = new IvParameterSpec(initParam); // 指定加密的算法、工作模式和填充方式 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec,ivSpec); byte[] encryptedBytes = cipher.doFinal(contentByte); String encodedString = Base64.getEncoder().encodeToString(encryptedBytes); return encodedString; } public static String aesDecry(String content,String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException { byte[] contentByte = Base64.getDecoder().decode(content); byte[] keyByte = key.getBytes(); //初始化一个密钥对象 SecretKeySpec keySpec = new SecretKeySpec(keyByte ,AES); //初始化一个初始向量,不传入的话,则默认用全0的初始向量 byte[] initParam = IV_STRING.getBytes(); IvParameterSpec ivSpec = new IvParameterSpec(initParam); // 指定加密的算法、工作模式和填充方式 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec,ivSpec); byte[] result = cipher.doFinal(contentByte); return new String(result,UTF8); } }

文章永久链接:https://tech.souyunku.com/19356

未经允许不得转载:搜云库技术团队 » Java-AES加密解密

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们