笔记:
import org.junit.Test;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AES {
public static String ALGGORITHM = "AES";
public static byte[] encory(String content,String password) throws Exception{
KeyGenerator kgen = KeyGenerator.getInstance(ALGGORITHM);
//用户密码作为随机数初始化
kgen.init(128,new SecureRandom(password.getBytes()));
//得到一个密钥
SecretKey secretKey = kgen.generateKey();
//对密钥进行基本的编码
byte[] encodedFormat = secretKey.getEncoded();
//转换成AES专用密钥
SecretKeySpec key = new SecretKeySpec(encodedFormat,ALGGORITHM);
//创建一个密码器
Cipher cipher = Cipher.getInstance(ALGGORITHM);
byte[] byteContent = content.getBytes();
//开始加密了
cipher.init(Cipher.ENCRYPT_MODE,key);
byte[] result = cipher.doFinal(byteContent);
return result;
}
public static byte[] decrypt(byte[] content,String password) throws Exception{
//创建AES的key生产者
KeyGenerator kgen = KeyGenerator.getInstance(ALGGORITHM);
//利用用户密码最为随机数初始化
kgen.init(128,new SecureRandom(password.getBytes()));
//根据用户密码,生成英特密钥 (所有对称算法通用)
SecretKey secretKeySpec = kgen.generateKey();
//对密钥进行基本的编码
byte[] enCodeFormat = secretKeySpec.getEncoded();
//转换成AES专用的密钥 RoundKey
SecretKeySpec key = new SecretKeySpec(enCodeFormat,ALGGORITHM);
//创建一个密码器
Cipher cipher = Cipher.getInstance(ALGGORITHM);
//解密
cipher.init(Cipher.DECRYPT_MODE,key);
byte[] result = cipher.doFinal(content);
return result;
}
@Test
public void testAES() throws Exception{
String content = "wwy";
String password = "123dsad";
byte[] encory = encory(content,password);
System.out.println("加密数据: " + new String(encory));
byte[] decory = decrypt(encory,password);
System.out.println("解密的数据: " + new String(decory));
}
}