代码如下:
package com.etoak.test;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
public class TestEncrypt {
//private static final byte[] KEYS = new byte[]{100, 51, 78, 107, 97, 71, 120, 104, 100, 51, 78, 107, 97, 71, 120, 104, 100, 51, 78, 107, 97, 65, 61, 61};
private static byte[] KEYS = null;
private static String key = null;
public static void main(String[] args) {
// region 计算KEYS
// AESConstants.AES_BLOCK_SIZE默认值为16
// IV length: must be 16 bytes long
Base64.Encoder encoder = Base64.getEncoder();
Base64.Decoder decoder = Base64.getDecoder();
String base = "wsdhlawsdhlawsdh";
String s = encoder.encodeToString(base.getBytes());
KEYS = s.getBytes();
// endregion
String uri = "待加密字符串";
String encrypt = encrypt(uri);
System.out.println("当前加密后URI:" + encrypt);
System.out.println("当前解密后URI:" + decrypt(encrypt));
}
private static String encrypt(String planPasswd) {
try {
String key = getLegalKey();
String iv = getLegalKey();
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = planPasswd.getBytes();
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength += blockSize - plaintextLength % blockSize;
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(1, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return encode(encrypted).trim();
} catch (Exception var11) {
return planPasswd;
}
}
private static String decrypt(String encryptedPasswd) {
String key = getLegalKey();
String iv = getLegalKey();
try {
byte[] encrypted1 = decode(encryptedPasswd);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(2, keyspec, ivspec);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString.trim();
} catch (Exception var9) {
return encryptedPasswd;
}
}
private static String getLegalKey() {
if (key == null) {
Base64.Decoder decoder = Base64.getDecoder();
try {
key = new String(decoder.decode(new String(KEYS)), "UTF-8");
} catch (UnsupportedEncodingException var2) {
var2.printStackTrace();
}
}
return key;
}
private static String encode(byte[] byteArray) {
return new String(Base64.getEncoder().encode(byteArray));
}
private static byte[] decode(String base64EncodedString) {
return Base64.getDecoder().decode(base64EncodedString);
}
}