package com.matrix.util.cipher;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AES128CommonUtils
{
/**
* 密钥算法
*/
public static final String KEY_ALGORITHM = "AES";
/**
* 加解密算法/工作模式/填充方式
*/
public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
/**
* 密钥长度
*/
public static final int KEY_SIZE = 16 * 8;
/**
* 生成密钥
*
* @return 二进制密钥
* @throws Exception
*/
public static byte[] initKey() throws Exception
{
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
kg.init(KEY_SIZE);
SecretKey secretKey = kg.generateKey();
return secretKey.getEncoded();
}
/**
* 转换密钥
*
* @param key
* 二进制密钥
* @return Key 密钥
*/
public static Key toKey(byte[] key)
{
SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
return secretKey;
}
/**
* 解密
* @param data 待解密数据
* @param key 密钥
* @return 解密数据
* @throws Exception
*/
public static byte[] decrypt(byte[] data, byte[] key) throws Exception
{
Key k = toKey(key);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, k);
return cipher.doFinal(data);
}
/**
* 加密
* @param data 待加密数据
* @param key 密钥
* @return 加密后数据
* @throws Exception
*/
public static byte[] encrypt(byte[] data, byte[] key) throws Exception
{
Key k = toKey(key);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, k);
return cipher.doFinal();
}
}
AES128
最新推荐文章于 2024-06-06 10:33:18 发布