import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* @Auther: chenhuan
* @Date: 2018/8/30 11:12
* @Description:
*/
public class AESTest {
/**
* AES加密字符串
* @param content:需要被加密的字符串
* @param password:加密需要的密码
* @return
*/
public static byte[] encrypt(String content,String password){
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");//创建AES的key生产者
kgen.init(128,new SecureRandom(password.getBytes()));//利用password作为随机数初始化出128位的key生产者
SecretKey secretKey = kgen.generateKey();//生成密钥
byte[] encoded = secretKey.getEncoded();//返回基本编码格式的密钥
SecretKeySpec key=new SecretKeySpec(encoded,"AES");//转换成AES专用密钥
Cipher cipher = Cipher.getInstance("AES");//创建密码器
byte[] byteContent = content.getBytes();
cipher.init(Cipher.ENCRYPT_MODE,key);//初始化为加密模式的密码器
byte[] result = cipher.doFinal(byteContent);
return result;
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
/**
* AES解密
* @param content AES加密之后的内容
* @param password 加密时用的密码
* @return
*/
public static byte[] decrypt(byte[] content,String password){
try {
KeyGenerator kgen=KeyGenerator.getInstance("AES");//创建AES的key生产者
kgen.init(128,new SecureRandom(password.getBytes()));//初始化
SecretKey secretKey = kgen.generateKey();//生产密钥
byte[] encoded = secretKey.getEncoded();//生产基本编码格式的密钥
SecretKeySpec key=new SecretKeySpec(encoded,"AES");//转换成AES专用密钥
Cipher aes = Cipher.getInstance("AES");//创建密码器
aes.init(Cipher.DECRYPT_MODE,key);//初始化为解密模式的密码器
byte[] result = aes.doFinal(content);
return result;
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String name="艾弗森";
byte[] bytes = name.getBytes();
byte[] data = encrypt(name, "123456");
for (byte b : bytes) {
System.out.println(b);
}
byte[] decrypt = decrypt(data, "123456");
String _name=new String(decrypt);
for (byte _b : decrypt) {
System.out.println(_b);
}
System.out.println(_name);
}
}
AES加密与解密
最新推荐文章于 2025-04-22 10:12:00 发布