import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
String amountStr = "123456";
String AES_IV = "05U1GlzbvBmS9UVz+out4Q==";
String AES_KEY = "D5M2+rt7out0Oc23K+YqYr==";
try {
String str = EncryptUtil.AESEncryptEncode(amountStr,AES_IV,AES_KEY);
System.out.println(str); // 这里输出:oks9F0DqTtVWvAZeFOaaVw==
} catch(Exception e) {
}
}
}
class EncryptUtil {
private static final String ENCODE = "UTF-8";
private static final String AES = "AES";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
/**
* AES加密
* @param content 加密内容
* @param AES_IV 加密偏移量
* @param AES_KEY 加密密钥
* @return 密文
* @throws Exception 加密过程中出现的异常
*/
public static String AESEncryptEncode(String content,String AES_IV,String AES_KEY) throws Exception{
Base64.Decoder decoder = Base64.getDecoder();
byte[] keyByte = decoder.decode(AES_KEY);
int base = 16;
if (keyByte.length % base != 0) {
int groups = keyByte.length / base + 1;
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
keyByte = temp;
}
SecretKeySpec secretKeySpec = new SecretKeySpec(keyByte,AES);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE,secretKeySpec,new IvParameterSpec(decoder.decode(AES_IV)));
byte[] result = cipher.doFinal(content.getBytes(ENCODE));
return Base64.getEncoder().encodeToString(result);
}
}