100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 数据AES加密安全传输之后台JAVA加密解密

数据AES加密安全传输之后台JAVA加密解密

时间:2022-06-24 18:18:31

相关推荐

数据AES加密安全传输之后台JAVA加密解密

AES是开发中常用的加密算法之一。AES的算法总是相同的, 但经常遇到前端加密结果,后台无法解密,这是因为加密设置的参数不一致导致的。如果要保持一致,必须使下列参数一致密钥长度、加密模式、填充方式、初始向量。

一、引入Java类

import javax.crypto.*;//AES加密解密import sun.misc.*;//BASE64转码

二、加密

/*** 加密*/public static String encrypt(String content,String CRYPT_KEY,String IV_STRING) {byte[] encryptedBytes = new byte[0];try {byte[] byteContent = content.getBytes("UTF-8");//keybyte[] 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 {// base64 解码byte[] encryptedBytes = new BASE64Decoder().decodeBuffer(content);//keybyte[] 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";//keyString 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));}

五、输出结果

Java后台加密解密与上一篇文章《数据AES加密安全传输之前端JS加密解密》对应

参考:/coyote1994/article/details/52368921

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。