org.bouncycastle bcprov-jdk15on 1.64 public class EncryptUtils { private static final String SECRET = "AES"; private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding"; static { Security.addProvider(new BouncyCastleProvider()); } /** * AES加密ECB模式PKCS7Padding填充方式 * @param str 字符串 * @param key 密钥 * @return 加密字符串 * @throws Exception 异常信息 */ public static String aes256ECBPkcs7PaddingEncrypt(String str, String key) throws Exception { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, SECRET)); byte[] doFinal = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)); return new String(Base64.getEncoder().encode(doFinal)); } /** * AES解密ECB模式PKCS7Padding填充方式 * @param str 字符串 * @param key 密钥 * @return 解密字符串 * @throws Exception 异常信息 */ public static String aes256ECBPkcs7PaddingDecrypt(String str, String key) throws Exception { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, SECRET)); byte[] doFinal = cipher.doFinal(Base64.getDecoder().decode(str)); return new String(doFinal); } } public static void main(String[] args) throws Exception { String str = "a1234567"; System.out.println("字符串:" + str); String encryptStr = EncryptUtils.aes256ECBPkcs7PaddingEncrypt(str, "AES454-HTJSQ9-IT"); System.out.println("加密后字符串:" + encryptStr); String decryptStr = EncryptUtils.aes256ECBPkcs7PaddingDecrypt(encryptStr, "AES454-HTJSQ9-IT"); System.out.println("解密后字符串:" + decryptStr); }