import javax.crypto.*;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class TestAes {
static final String ALGORITHM="AES";
public static SecretKey generateKey() throws NoSuchAlgorithmException {
KeyGenerator secretGenerator=KeyGenerator.getInstance(ALGORITHM);//AES 128
SecureRandom secureRandom=new SecureRandom();//随机数
secretGenerator.init(secureRandom);//初始化
SecretKey secretKey=secretGenerator.generateKey();
return secretKey;
}
static Charset charset=Charset.forName("UTF-8");
public static byte[] encrypt(String content, SecretKey secretKey) throws BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
return aes(content.getBytes(charset),Cipher.ENCRYPT_MODE,secretKey);
}
public static String decrypt(byte[] contentArray, SecretKey secretKey) throws BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
byte[] result = aes(contentArray,Cipher.DECRYPT_MODE,secretKey);
return new String(result,"UTF-8");
}
public static byte[] aes(byte[] contentArray,int mode,SecretKey secretKey) throws BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
Cipher cipher =Cipher.getInstance(ALGORITHM);
cipher.init(mode,secretKey);
byte[] result=cipher.doFinal(contentArray);
return result;
}
public static void main(String[] args) throws BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException {
String content="hello world 你好,我是xxx";
SecretKey secretKey=generateKey();
byte[] encryptResult=encrypt(content,secretKey);
System.out.println("加密后的结果为" +new String(encryptResult,"utf-8"));
String decryptResult = decrypt(encryptResult,secretKey);
System.out.println("解密后的结果为"+decryptResult);
}
}
初中级面试装逼必备