SpringBoot + Vue 实现 AES 加密和 AES 工具类总结
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtil {
// AES加密
public static String encryptAES(String content, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
byte[] keyBytes = new byte[16];
System.arraycopy(key.getBytes(), 0, keyBytes, 0, key.getBytes().length);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal(content.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
// AES解密
public static String decryptAES(String encryptedContent, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
byte[] keyBytes = new byte[16];
System.arraycopy(key.getBytes(), 0, keyBytes, 0, key.getBytes().length);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedContent));
return new String(decrypted);
}
}
这个简单的AES工具类提供了加密和解密的方法,使用时只需要传入需要加密或解密的内容和密钥即可。注意,密钥长度必须是16个字节。在实际应用中,密钥应当采用安全的方式管理和传输。
评论已关闭