因为公司业务需要,要使用AES256加解密,但是java默认支持128位加密规范,如果想支持256位加密规范,就需要使用无限制JCE策略文件。过程中遇到以下问题,以及解决如下:
报错:java.security.NoSuchProviderException: No such provider: BC
解决:Java默认支持的填充方式是PKCS5Padding,所以需要引用第三方jar包bouncycastle组件来让Java里面支持PKCS7Padding填充方式
引入jar包:
https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk16/1.46
<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk16 -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
在类中加入静态代码块
/**
* 使用PKCS7Padding填充必须添加一个支持PKCS7Padding的Provider
* 类加载的时候添加进去
*/
static{
try{
Security.addProvider(new BouncyCastleProvider());
}catch(Exception e){
e.printStackTrace();
}
}
报错:java.security.InvalidKeyException: Illegal key size or default parameters
解决:java默认支持128位加密规范,如果想支持256位加密规范,就需要使用无限制JCE策略文件,覆盖掉jdk中的security包下的local_policy.jar 和 US_export_policy.jar
C:\Program Files\Java\jre1.8.0_91\lib\security
C:\Program Files\Java\jdk1.8.0_91\jre\lib\security
下载地址:
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
代码如下:
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.Base64;
/**
* @ClassName AESEncrypt
* @Date 2019/8/26 16:10
* @Version 1.0
*/
public class AESEncrypt {
public static final String ALGORITHM = "AES/ECB/PKCS7Padding";
/**
* 使用PKCS7Padding填充必须添加一个支持PKCS7Padding的Provider
* 类加载的时候添加进去
*/
static{
try{
Security.addProvider(new BouncyCastleProvider());
}catch(Exception e){
e.printStackTrace();
}
}
public static String Aes256Encode(String str, byte[] key) {
byte[] result = null;
try {
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
result = cipher.doFinal(str.getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
return new String(Base64.getEncoder().encode(result));
}
public static String Aes256Decode(String str, byte[] key) {
byte[] bytes = Base64.getDecoder().decode(str);
String result = null;
try {
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decoded = cipher.doFinal(bytes);
result = new String(decoded, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) throws Exception {
String content = "CD1000250201906121742434441";
String aesKey = "0a091b3aa4324435aab703142518a8f7";
String Result = FuluAESEncrypt.Aes256Encode(content, aesKey.getBytes());
System.out.println("加密結果:" + Result);
String value = FuluAESEncrypt.Aes256Decode(Result, aesKey.getBytes());
System.out.println("解密結果:" + value);
}
}