作者:phperint | 来源:互联网 | 2023-09-14 14:28
AES是开发中常用的加密算法之一。AES的算法总是相同的, 但经常遇到前端加密结果,后台无法解密,这是因为加密设置的参数不一致导致的。如果要保持一致,必须使下列参数一致密钥长度、加密模式、填充方式、初始向量。
一、引入Java类
import javax.crypto.*;
import sun.misc.*;
二、加密
public static String encrypt(String content,String CRYPT_KEY,String IV_STRING) {byte[] encryptedBytes = new byte[0];try {byte[] byteContent = content.getBytes("UTF-8");byte[] enCodeFormat = CRYPT_KEY.getBytes();SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");byte[] initParam = IV_STRING.getBytes();IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);encryptedBytes = cipher.doFinal(byteContent);} catch (Exception e) {System.out.println("AES encrypt Exception,cOntent= {"+content+"},Exception = {"+e.getStackTrace()+"}");}return new BASE64Encoder().encode(encryptedBytes);}
三、解密
public static String decrypt(String content,String CRYPT_KEY,String IV_STRING) {try {byte[] encryptedBytes = new BASE64Decoder().decodeBuffer(content);byte[] enCodeFormat = CRYPT_KEY.getBytes();SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");byte[] initParam = IV_STRING.getBytes();IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);byte[] result = cipher.doFinal(encryptedBytes);return new String(result, "UTF-8");} catch (Exception e) {System.out.println( "AES decrypt Exception,cOntent= {"+content+"},Exception = {"+e.getStackTrace()+"}");}return null;}
四、测试
public static void main(String[] args) {String CRYPT_KEY = "0123456789abcdef";String IV_STRING = "0123456789abcdef";String content = "12345";System.out.println("原文:"+content);String contenCrypt = encrypt(content.toString().replaceAll("(\r\n|\r|\n|\n\r)",""),CRYPT_KEY,IV_STRING);System.out.println("加密:"+contenCrypt);System.out.println("解密:"+decrypt(contenCrypt,CRYPT_KEY,IV_STRING));System.out.println("JS加密密文解密:"+decrypt("xWngUO1XD+BavHm1YkdTxA==",CRYPT_KEY,IV_STRING));}
五、输出结果
![在这里插入图片描述](https://img2.php1.cn/3cdc5/3ecd/696/7adf80568a14db44.png)
Java后台加密解密与上一篇文章《数据AES加密安全传输之前端JS加密解密》对应
参考:https://blog.csdn.net/coyote1994/article/details/52368921