Java 里的AES/CBC/PKCS7Padding加解密,由于Java对PKCS7Padding支持不是很好,所以在网上找了许多类似资料,各有各的实现,最后总结下来是很简单的。也不费话了,直接上代码。
public final class AesUtils { private static final String CHARSET_NAME = "UTF-8"; private static final String AES_NAME = "AES"; public static final String ALGORITHM = "AES/CBC/PKCS7Padding"; static { Security.addProvider(new BouncyCastleProvider()); } /** * 加密 * * @param content * @param key * @return */ public static String encrypt(@NotNull String content, @NotNull String key) { byte[] result = null; try { Cipher cipher = Cipher.getInstance(ALGORITHM); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(CHARSET_NAME), AES_NAME); AlgorithmParameterSpec paramSpec = new IvParameterSpec(new byte[16]); cipher.init(Cipher.ENCRYPT_MODE, keySpec, paramSpec); result = cipher.doFinal(content.getBytes(CHARSET_NAME)); } catch (Exception ex) { Throwables.propagate(ex); } return Base64.encodeBase64String(result); } /** * 解密 * * @param content * @param key * @return */ public static String decrypt(@NotNull String content, @NotNull String key) { try { Cipher cipher = Cipher.getInstance(ALGORITHM); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(CHARSET_NAME), AES_NAME); AlgorithmParameterSpec paramSpec = new IvParameterSpec(new byte[16]); cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec); return new String(cipher.doFinal(Base64.decodeBase64(content)), CHARSET_NAME); } catch (Exception ex) { Throwables.propagate(ex); } return StringUtils.EMPTY; } }