import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESUtil {
private static final String DEFAULT_KEY="hj7x89H$yuBI0456";
private static final String DEFAULT_IV ="NIfb&95GUY86Gfgh";
/**
* @Ddescription AES加密
* @param key 16位秘钥
* @param iv 向量iv
* @param plaintext 明文
* @return 密文
*/
public static String encrypt(String key, String iv, String plaintext) throws Exception {
Cipher cipher = getCipher(key,iv,Cipher.ENCRYPT_MODE);
byte[] bytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(bytes);
}
/**
* @Description AES解密
* @param key 16位秘钥
* @param iv 向量iv
* @param ciphertext 密文
* @return 明文
*/
public static String decrypt(String key, String iv, String ciphertext) throws Exception {
Cipher cipher = getCipher(key,iv,Cipher.DECRYPT_MODE);
byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
return new String(bytes,StandardCharsets.UTF_8);
}
private static Cipher getCipher(String key, String iv,int mode) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
cipher.init(mode, keySpec, ivSpec);
return cipher;
}
public static void main(String[] args) throws Exception {
String text = "JDK 中是由名为 “SunJCE” 的提供商提供密钥算法的,如果没有指定其他提供商,则会默认使用该提供商的密钥算法。如果要使用特定的算法,而对该算法 Oracle 公司没有提供支持,那么也可以指定其他的提供商。";
String ciphertext = encrypt(DEFAULT_KEY,DEFAULT_IV,text);
System.out.println(ciphertext);
String plaintext = decrypt(DEFAULT_KEY,DEFAULT_IV,ciphertext);
System.out.println(plaintext);
}
}
标签:AES,JAVA,String,param,iv,Cipher,key,cipher,加密算法
From: https://www.cnblogs.com/xiaogblog/p/17362325.html