AES 加密

时间:2021-01-10 05:29:54
package com.sprucetec.tms.utils;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; public class AES {
//密钥算法
public static final String KEY_ALGORITHM = "AES"; //加解密算法/工作模式/填充方式
public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding"; /**
* 生成密钥
*/
public static String initkey() throws Exception {
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM); //实例化密钥生成器
kg.init(128); //初始化密钥生成器:AES要求密钥长度为128,192,256位
SecretKey secretKey = kg.generateKey(); //生成密钥
return Base64.encode(secretKey.getEncoded()); //获取二进制密钥编码形式
} /**
* 加密数据
* @param data 待加密数据
* @param key 密钥
* @return 加密后的数据
* */
public static String encrypt(String data, String key) throws Exception {
Key k = new SecretKeySpec(key.getBytes("UTF-8"), KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); //实例化Cipher对象,它用于完成实际的加密操作
cipher.init(Cipher.ENCRYPT_MODE, k); //初始化Cipher对象,设置为加密模式
return Base64.encode(cipher.doFinal(data.getBytes("UTF-8"))); //执行加密操作。加密后的结果用Base64编码进行传输
} /**
* 解密数据
* @param data 待解密数据
* @param key 密钥
* @return 解密后的数据
* */
public static String decrypt(String data, String key) throws Exception {
Key k = new SecretKeySpec(key.getBytes("UTF-8"), KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, k); //初始化Cipher对象,设置为解密模式
return new String(cipher.doFinal(Base64.decode(data))); //执行解密操作
} public static void main(String[] args) throws Exception {
System.out.println(AES.encrypt("asdf", "1234560000000000"));
System.out.println(AES.decrypt("sT4nPMyTugE2pQnCNQPtJw==", "1234560000000000"));
}
}