AES加密解密(工具類+例項)
阿新 • • 發佈:2018-12-12
工具類:
package com.valueaddedservices.web.utils; import java.util.Date; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import com.snake.bsys.common.support.DateUtil; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * 類名稱:AESUtils 類描述: AES加解密工具類 建立人:qiuying * 建立時間:2018年11月28日 9:07:01 * * @version */ public class AESUtils { private static String algorithm = "AES"; /** * 加密 * @param str * @param key * @return * @throws Exception */ public static String aesEncrypt(String str, String key) throws Exception { if (str == null || key == null) return null; Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), algorithm)); byte[] bytes = cipher.doFinal(str.getBytes("utf-8")); return new BASE64Encoder().encode(bytes); } /** * 解密 * @param str * @param key * @return * @throws Exception */ public static String aesDecrypt(String str, String key) throws Exception { if (str == null || key == null) return null; Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), algorithm)); byte[] bytes = new BASE64Decoder().decodeBuffer(str); bytes = cipher.doFinal(bytes); return new String(bytes, "utf-8"); } }
例項:
String aesEncrypt = AESUtils.aesEncrypt(加密內容, 祕鑰);