AES加解密工具類 AESUtil
阿新 • • 發佈:2018-12-15
pom.xml先引入依賴:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.60</version>
</dependency>
import org.apache.commons.net.util.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * @Auther: * @Date: 2018/10/19 15:49 * @Description: */ public class AESUtil { static Logger logger = LoggerFactory.getLogger(AESUtil.class); // 金鑰 public static String key = "AD42F6697B035B7580E4FEF93BE20BAD"; private static String charset = "utf-8"; // 偏移量 private static int offset = 16; // 加密器型別:加密演算法為AES,加密模式為CBC,補碼方式為PKCS5Padding private static String transformation = "AES/CBC/PKCS5Padding"; // 演算法型別:用於指定生成AES的金鑰 private static String algorithm = "AES"; /** * 加密 * * @param content * @return */ public static String encrypt(String content) { return encrypt(content, key); } /** * 解密 * * @param content * @return */ public static String decrypt(String content) { return decrypt(content, key); } /** * 加密 * * @param content 需要加密的內容 * @param key 加密密碼 * @return */ public static String encrypt(String content, String key) { try { //構造金鑰 SecretKeySpec skey = new SecretKeySpec(key.getBytes(), algorithm); //建立初始向量iv用於指定金鑰偏移量(可自行指定但必須為128位),因為AES是分組加密,下一組的iv就用上一組加密的密文來充當 IvParameterSpec iv = new IvParameterSpec(key.getBytes(), 0, offset); //建立AES加密器 Cipher cipher = Cipher.getInstance(transformation); byte[] byteContent = content.getBytes(charset); //使用加密器的加密模式 cipher.init(Cipher.ENCRYPT_MODE, skey, iv); // 加密 byte[] result = cipher.doFinal(byteContent); //使用BASE64對加密後的二進位制陣列進行編碼 return new Base64().encodeToString(result); } catch (Exception e) { logger.info("", e); } return null; } /** * AES(256)解密 * * @param content 待解密內容 * @param key 解密金鑰 * @return 解密之後 * @throws Exception */ public static String decrypt(String content, String key) { try { SecretKeySpec skey = new SecretKeySpec(key.getBytes(), algorithm); IvParameterSpec iv = new IvParameterSpec(key.getBytes(), 0, offset); Cipher cipher = Cipher.getInstance(transformation); //解密時使用加密器的解密模式 cipher.init(Cipher.DECRYPT_MODE, skey, iv);// 初始化 byte[] result = cipher.doFinal(new Base64().decode(content)); return new String(result); // 解密 } catch (Exception e) { logger.info("", e); } return null; } public static void main(String[] args) { String s = "hello World!123.加解密"; String encryptResultStr = encrypt(s); // 加密 System.out.println("加密前:" + s); System.out.println("加密後:" + encryptResultStr); // 解密 System.out.println("解密後:" + decrypt(encryptResultStr)); } }