标签:bit key catch final md5 param padding class char
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); } }
标签:bit key catch final md5 param padding class char
原文地址:https://www.cnblogs.com/chenss15060100790/p/9080497.html