调用方式:
// 去除JCE加密限制,只限于Java1.8
try {
Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, false);
} catch (ClassNotFoundException | NoSuchFieldException |
SecurityException | IllegalArgumentException | IllegalAccessException ex) {
}
byte [] newkey = new byte[32];
System.arraycopy(key.getBytes(), 0, newkey, 0, key.getBytes().length);
for(int i = key.length() ;i < 32;i ++){
newkey[i] = (byte) 0x20;
}
String decodeTest="";
try {
String text = "0qZc/yQqCkPwMnWkzht4t520pn9IIo9yKciYvuXFCt4=";
decodeTest = decrypt( text,newkey);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("解密结果: " + decodeTest);
函数定义:
private static final String KEY_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";
public static final String ENCODING = "UTF-8";
private static String key = "Z016770e6f4f91.83Abez23*";
private static byte[] m_iv =
{0x12,0x34,0x56,0x78,(byte) 0x90,(byte) 0xab,(byte) 0xcd,(byte) 0xef,
0x12,0x34,0x56,0x78,(byte) 0x90,(byte) 0xab,(byte) 0xcd,(byte) 0xef};
static {
// 是PKCS7Padding填充方式,则需要添加Bouncy Castle支持
Security.addProvider(new BouncyCastleProvider());
}
public static String decrypt(String str, byte[] key) throws Exception {
try {
Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, false);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"));
byte[] doFinal = cipher.doFinal(Base64.getDecoder().decode(str));
return new String(doFinal);
} catch (ClassNotFoundException | NoSuchFieldException |
SecurityException | IllegalArgumentException | IllegalAccessException ex) {
}
return "";
}
"AES/ECB/PKCS7Padding"加密方式需要Bouncy castle包的支持,安装Bouncy castle参考以下链接:https://blog.csdn.net/qq_41546054/article/details/120766852