JAVA中使用AES256加密
點(diǎn)擊上方藍(lán)色字體,選擇“標(biāo)星公眾號(hào)”
優(yōu)質(zhì)文章,第一時(shí)間送達(dá)
76套java從入門到精通實(shí)戰(zhàn)課程分享
前言:java默認(rèn)支持128位加密規(guī)范,如果想支持256位加密規(guī)范,就需要使用無限制JCE策略文件,而現(xiàn)在Android端AES256的加密填充方式一般是PKCS7Padding,JAVA支持PKCS5Padding,雖然PKCS7Padding和PKCS5Padding除了命名不同其他沒什么區(qū)別,但是為了規(guī)范,我們還是需要引入第三方j(luò)ar包bouncycastle來使我們的JAVA支持這個(gè)填充模式,所以接下來我們先做好準(zhǔn)備工作
1.在pom文件中引入第三方j(luò)ar包
若不引入則無法支持 PKCS7Padding 填充規(guī)范,使用PKCS7Padding作為填充方式會(huì)拋出不支持這個(gè)填充規(guī)范的異常
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.56</version>
</dependency>
2.下載無限制JCE策略文件,并覆蓋到JDK和JRE中
若不下載并覆蓋原有JCE策略文件,則無法支持 256 加密規(guī)范,密匙字符串長(zhǎng)度只能為16而不是32,使用32長(zhǎng)度的字符串作為密匙會(huì)拋出相應(yīng)異常
C:\Program Files\Java\jre1.8.0_91\lib\security
C:\Program Files\Java\jdk1.8.0_91\jre\lib\security
(自己的JAVA_HOME路徑)
無限制JCE策略文件下載地址:
JDK7的下載地址: https://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
JDK8的下載地址: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
話不多說,上干貨
/**
* @Title: AESUtils.java
* @Package com.guanhuaWang.util.AES
* @Description: AES密碼工具類
* @author Guanhua Wang
* @date 2019年1月15日16:22:57
* @version V1.0
*/
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;
/**
* @author GuanHua Wang
* @ClassName: AESUtils
* @Description: aes對(duì)稱加密解密工具類, 注意密鑰不能隨機(jī)生機(jī), 不同客戶端調(diào)用可能需要考慮不同Provider,
* 考慮安卓與IOS不同平臺(tái)復(fù)雜度,簡(jiǎn)化不使用Provider
* @date 2019年1月15日16:00:39
*/
public class AESUtils {
/***默認(rèn)向量常量**/
public static final String IV = "1234567890123456";
private final static Logger logger = LoggerFactory.getLogger(AESUtils.class);
/**
* 使用PKCS7Padding填充必須添加一個(gè)支持PKCS7Padding的Provider
* 類加載的時(shí)候就判斷是否已經(jīng)有支持256位的Provider,如果沒有則添加進(jìn)去
*/
static {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
}
/**
* 加密 128位
*
* @param content 需要加密的原內(nèi)容
* @param pkey 密匙
* @return
*/
public static byte[] aesEncrypt(String content, String pkey) {
try {
//SecretKey secretKey = generateKey(pkey);
//byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec skey = new SecretKeySpec(pkey.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");// "算法/加密/填充"
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skey, iv);//初始化加密器
byte[] encrypted = cipher.doFinal(content.getBytes("UTF-8"));
return encrypted; // 加密
} catch (Exception e) {
logger.info("aesEncrypt() method error:", e);
}
return null;
}
/**
* 獲得密鑰
*
* @param secretKey
* @return
* @throws Exception
*/
private static SecretKey generateKey(String secretKey) throws Exception {
//防止linux下 隨機(jī)生成key
Provider p = Security.getProvider("SUN");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", p);
secureRandom.setSeed(secretKey.getBytes());
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(secureRandom);
// 生成密鑰
return kg.generateKey();
}
/**
* @param content 加密前原內(nèi)容
* @param pkey 長(zhǎng)度為16個(gè)字符,128位
* @return base64EncodeStr aes加密完成后內(nèi)容
* @throws
* @Title: aesEncryptStr
* @Description: aes對(duì)稱加密
*/
public static String aesEncryptStr(String content, String pkey) {
byte[] aesEncrypt = aesEncrypt(content, pkey);
System.out.println("加密后的byte數(shù)組:" + Arrays.toString(aesEncrypt));
String base64EncodeStr = Base64.encodeBase64String(aesEncrypt);
System.out.println("加密后 base64EncodeStr:" + base64EncodeStr);
return base64EncodeStr;
}
/**
* @param content base64處理過的字符串
* @param pkey 密匙
* @return String 返回類型
* @throws Exception
* @throws
* @Title: aesDecodeStr
* @Description: 解密 失敗將返回NULL
*/
public static String aesDecodeStr(String content, String pkey) throws Exception {
try {
System.out.println("待解密內(nèi)容:" + content);
byte[] base64DecodeStr = Base64.decodeBase64(content);
System.out.println("base64DecodeStr:" + Arrays.toString(base64DecodeStr));
byte[] aesDecode = aesDecode(base64DecodeStr, pkey);
System.out.println("aesDecode:" + Arrays.toString(aesDecode));
if (aesDecode == null) {
return null;
}
String result;
result = new String(aesDecode, "UTF-8");
System.out.println("aesDecode result:" + result);
return result;
} catch (Exception e) {
System.out.println("Exception:" + e.getMessage());
throw new Exception("解密異常");
}
}
/**
* 解密 128位
*
* @param content 解密前的byte數(shù)組
* @param pkey 密匙
* @return result 解密后的byte數(shù)組
* @throws Exception
*/
public static byte[] aesDecode(byte[] content, String pkey) throws Exception {
//SecretKey secretKey = generateKey(pkey);
//byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec skey = new SecretKeySpec(pkey.getBytes(), "AES");
IvParameterSpec iv = new IvParameterSpec(IV.getBytes("UTF-8"));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");// 創(chuàng)建密碼器
cipher.init(Cipher.DECRYPT_MODE, skey, iv);// 初始化解密器
byte[] result = cipher.doFinal(content);
return result; // 解密
}
public static void main(String[] args) throws Exception {
//明文
String content = "qq245635595";
//密匙
String pkey = "wwwwwwwwwwwwwww1wwwwwwwwwwwwwww1";
System.out.println("待加密報(bào)文:" + content);
System.out.println("密匙:" + pkey);
String aesEncryptStr = aesEncryptStr(content, pkey);
System.out.println("加密報(bào)文:" + aesEncryptStr);
String aesDecodeStr = aesDecodeStr(aesEncryptStr, pkey);
System.out.println("解密報(bào)文:" + aesDecodeStr);
System.out.println("加解密前后內(nèi)容是否相等:" + aesDecodeStr.equals(content));
}
}
控制臺(tái)輸出結(jié)果:
待加密報(bào)文:qq245635595
密匙:wwwwwwwwwwwwwww1wwwwwwwwwwwwwww1
加密后的byte數(shù)組:[-47, -57, -112, -16, -127, -101, 127, 67, -23, -47, -52, 38, 76, -56, 3, 98]
加密后 base64EncodeStr:0ceQ8IGbf0Pp0cwmTMgDYg==
加密報(bào)文:0ceQ8IGbf0Pp0cwmTMgDYg==
待解密內(nèi)容:0ceQ8IGbf0Pp0cwmTMgDYg==
base64DecodeStr:[-47, -57, -112, -16, -127, -101, 127, 67, -23, -47, -52, 38, 76, -56, 3, 98]
aesDecode:[113, 113, 50, 52, 53, 54, 51, 53, 53, 57, 53]
aesDecode result:qq245635595
解密報(bào)文:qq245635595
加解密前后內(nèi)容是否相等:true
加解密前后內(nèi)容一致,說明我們的AES256加密已經(jīng)完成
————————————————
版權(quán)聲明:本文為CSDN博主「Guanhua Wang」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。
原文鏈接:
https://blog.csdn.net/qq_35248009/article/details/86494884
粉絲福利:Java從入門到入土學(xué)習(xí)路線圖
??????

??長(zhǎng)按上方微信二維碼 2 秒
感謝點(diǎn)贊支持下哈 
