<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;
public class AESUtil {
private static final String transformation = "AES/ECB/PKCS5Padding";
public static String encode(String password, String str) {
try {
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.ENCRYPT_MODE, generateKey(password));
byte[] bytes = cipher.doFinal(str.getBytes());
return Base64.encodeBase64URLSafeString(bytes);
} catch (Exception e) {
return null;
}
}
public static String decode(String password, String str) {
try {
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.DECRYPT_MODE, generateKey(password));
return new String(cipher.doFinal(Base64.decodeBase64(str)));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Key generateKey(String password) throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password.getBytes());
keyGen.init(128, secureRandom);
return keyGen.generateKey();
}
}