Created
April 1, 2020 06:58
-
-
Save HoweChen/7620c146d4da256f5a9564f264a6d1ec to your computer and use it in GitHub Desktop.
[AES/CBC/PKCS7Padding加密解密] #Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://blog.csdn.net/java_zjh/article/details/80915655 | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment