AES是一种对称的加密和解密的算法,其用法如下:
package com.zys.demo.util; import lombok.extern.slf4j.Slf4j; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; /** * aes加密与解密,对称的 */ @Slf4j public class AesUtil { private static final Base64.Decoder decoder = Base64.getDecoder(); private static final Base64.Encoder encoder = Base64.getEncoder(); private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; /** * 加密 * * @param str 加密前的字符串 * @param key 加密KEY * @return */ public static String encrypt(String str, String key) throws Exception { if (key == null) { log.warn("Key为空null"); return null; } else if (key.length() != 16) { log.warn("Key长度不是16位"); return null; } byte[] raw = key.getBytes("utf-8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); IvParameterSpec iv = new IvParameterSpec(key.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(str.getBytes()); String encodedText = encoder.encodeToString(encrypted); return encodedText; } /** * 解密 * * @param str 解密前的字符串 * @param key 解密KEY * @return * @throws Exception */ public static String decrypt(String str, String key) throws Exception{ // 判断Key是否正确 if (key == null) { log.warn("Key为空null"); return null; } else if (key.length() != 16) { log.warn("Key长度不是16位"); return null; } byte[] raw = key.getBytes("utf-8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); IvParameterSpec iv = new IvParameterSpec(key.getBytes()); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] encrypted1 = decoder.decode(str); byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString; } public static void main(String[] args) throws Exception { String cKey = "2021071410123066"; // 需要加密的字串 String str = "123456"; String enString = encrypt(str, cKey); String DeString = decrypt(enString, cKey); } }
在使用时,需要给其指定加密和解密的盐值,且长度必须是16位。