Open dingqianwen opened 2 years ago
JAVA版本AES-CBC工具
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
@Slf4j
public class Aes128Util {
/**
* AES加密
*
* @param enStr 明文
* @return 密文 base64
*/
public static String encrypt(String enStr, String secretKey, String iv) {
try {
if (StringUtils.isEmpty(enStr)) {
return enStr;
}
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
SecretKeySpec sks = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, sks, ivParameterSpec);
byte[] encrypted = cipher.doFinal(enStr.getBytes());
return Base64.encodeBase64String(encrypted);
} catch (Exception ex) {
log.error("AES加密失败", ex);
throw new RuntimeException("AES加密失败!");
}
}
/**
* 解密
*
* @param encrypted 密文
* @return 明文
*/
public static String decrypt(String encrypted, String secretKey, String iv) {
try {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
SecretKeySpec sks = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, sks, ivParameterSpec);
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(original);
} catch (Exception ex) {
log.error("AES解密失败", ex);
throw new RuntimeException("AES解密失败!");
}
}
}
https://apidocs.cn/blog/tools/AES.html
丁乾文的博客,希望能够帮助到你!