import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public static String readFileAndEncodeAes(String filePath, String key) {
byte[] keyBytes = DigestUtils.md5(key);
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
byte[] aesBytes = encrypt(bytes, keyBytes);
return new String(Base64.encodeBase64(aesBytes), StandardCharsets.UTF_8);
log.warn("decodeAES error", e);
public static String encodeAES(String text, String key) {
byte[] keyBytes = DigestUtils.md5(key);
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
byte[] aesBytes = encrypt(bytes, keyBytes);
return new String(Base64.encodeBase64(aesBytes), StandardCharsets.UTF_8);
log.warn("encodeAES error", e);
public static String decodeAES(String text, String key) {
byte[] keyBytes = DigestUtils.md5(key);
byte[] debase64Bytes = Base64.decodeBase64(text);
return new String(decrypt(debase64Bytes, keyBytes), StandardCharsets.UTF_8);
log.warn("decodeAES error", e);
public static byte[] decodeAESBinary(String text, String key) {
byte[] keyBytes = DigestUtils.md5(key);
byte[] debase64Bytes = Base64.decodeBase64(text);
return decrypt(debase64Bytes, keyBytes);
log.warn("decodeAES error", e);
public static byte[] encrypt(byte[] text, byte[] key) throws Exception {
SecretKeySpec aesKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
return cipher.doFinal(text);
public static byte[] decrypt(byte[] text, byte[] key) throws Exception {
SecretKeySpec aesKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, aesKey);
return cipher.doFinal(text);