AES 加密
Posted 疯狂的妞妞
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AES 加密相关的知识,希望对你有一定的参考价值。
API提供了算法,代码很简单,拿走用吧……
import java.security.Key; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * 对称加密 * * @author ChenSS 2016/11/30 * @version 1.0 */ public class AES { private static IvParameterSpec iv = new IvParameterSpec("1234567890654321".getBytes()); public static void main(String[] args) { try { String key = MD5.hexBit16("a"); String encryStr = AES.encryptBase64("abcd", key); System.out.println("密文:" + encryStr); String decryStr = AES.decryptBase64(encryStr, key); System.out.println("明文:" + decryStr); } catch (Exception e) { e.printStackTrace(); } } public static String encryptBase64(String data, String publicKey) throws Exception { return Base64.byteArrayToBase64(encrypt(data.getBytes(), publicKey)); } public static String decryptBase64(String encryptedData, String privateKey) throws Exception { return new String(decrypt(Base64.base64ToByteArray(encryptedData), privateKey)); } public static String encryptHex(String data, String publicKey) throws Exception { return Hex.encodeToString(encrypt(data.getBytes(), publicKey)); } public static String decryptHex(String encryptedData, String privateKey) throws Exception { return new String(decrypt(Hex.decode(encryptedData.toCharArray()), privateKey)); } public static IvParameterSpec getIV(byte[] iv){ return new IvParameterSpec(iv); } public static Key getKey(byte[] key){ return new SecretKeySpec(key, "AES"); } public static byte[] encrypt(byte[] data, String key) throws Exception{ return encrypt(data, new SecretKeySpec(key.getBytes(), "AES"),iv); } public static byte[] decrypt(byte[] data, String key) throws Exception{ return decrypt(data, new SecretKeySpec(key.getBytes(), "AES"),iv); } /** * 加密 */ public static byte[] encrypt(byte[] data, Key keySpec, IvParameterSpec iv) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); return cipher.doFinal(data); } /** * 解密 */ public static byte[] decrypt(byte[] data, Key keySpec, IvParameterSpec iv) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec, iv); return cipher.doFinal(data); } }
以上是关于AES 加密的主要内容,如果未能解决你的问题,请参考以下文章
更新实现代码对称加密与解密剖析:AES,高级加密标准(Advanced Encryption Standard,缩写AES)