Commit f8f05099 authored by liaozan's avatar liaozan 🏀

Refactor AES128ECBWithPKCS7

Before this commit, The AES128ECBWithPKCS7 is encode/decode text to base64 default
Overloaded a method to support whether to convert with base64
parent 0f444738
package com.schbrain.common.util.cipher;
import cn.hutool.crypto.symmetric.AES;
import com.schbrain.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.Security;
......@@ -19,40 +21,55 @@ public class AES128ECBWithPKCS7 {
/**
* encrypt input text
*/
public static String encrypt(String input, String key) {
byte[] encrypted = encryptByte(input, key);
if (null == encrypted) {
return "";
}
return Base64.getEncoder().encodeToString(encrypted);
public static String encrypt(String input, String secretKey) {
return encrypt(input, secretKey, true);
}
public static byte[] encryptByte(String input, String key) {
byte[] encrypted;
try {
encrypted = new AES("ECB", "PKCS7Padding", key.getBytes(UTF_8)).encrypt(input);
} catch (Exception e) {
log.error("AES128ECBWithPKCS7 encrypt ({}) error! ", input, e);
return null;
/**
* encrypt input text
*/
public static String encrypt(String input, String secretKey, boolean toBase64) {
byte[] encrypted = encryptByte(input.getBytes(UTF_8), secretKey);
return toBase64 ? Base64.getEncoder().encodeToString(encrypted) : new String(encrypted, UTF_8);
}
return encrypted;
/**
* decrypt input text
*/
public static String decrypt(String input, String secretKey) {
return decrypt(input, secretKey, true);
}
/**
* decrypt input text
*/
public static String decrypt(String input, String key) {
return decryptByte(Base64.getDecoder().decode(input), key);
public static String decrypt(String input, String secretKey, boolean isBase64) {
byte[] bytes = isBase64 ? Base64.getDecoder().decode(input) : input.getBytes(UTF_8);
return new String(decryptByte(bytes, secretKey), UTF_8);
}
/**
* encrypt input bytes
*/
public static byte[] encryptByte(byte[] input, String secretKey) {
return createAes(secretKey).encrypt(input);
}
public static String decryptByte(byte[] input, String key) {
try {
byte[] output = new AES("ECB", "PKCS7Padding", key.getBytes(UTF_8)).decrypt(input);
return new String(output, UTF_8);
} catch (Exception e) {
log.error("AES128ECBWithPKCS7 decryptByte ({}) error!", new String(input, UTF_8), e);
return "";
/**
* decrypt input bytes
*/
public static byte[] decryptByte(byte[] input, String secretKey) {
return createAes(secretKey).decrypt(input);
}
/**
* create aes crypto
*/
private static AES createAes(String secretKey) {
if (StringUtils.isBlank(secretKey)) {
throw new BaseException("secretKey is blank!");
}
return new AES("ECB", "PKCS7Padding", secretKey.getBytes(UTF_8));
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment