|

楼主 |
发表于 2022-4-5 19:32:25
|
显示全部楼层
- import javax.crypto.BadPaddingException;
- import javax.crypto.Cipher;
- import javax.crypto.IllegalBlockSizeException;
- import javax.crypto.KeyGenerator;
- import javax.crypto.NoSuchPaddingException;
- import java.io.UnsupportedEncodingException;
- import java.nio.charset.Charset;
- import java.security.InvalidKeyException;
- import java.security.NoSuchAlgorithmException;
- import java.security.SecureRandom;
- import java.util.Base64;
- import java.util.Base64.Encoder;
- import javax.crypto.SecretKey;
- public class AESTest {
- static final String ALGORITHM="AES";
- public static SecretKey generatekey() throws NoSuchAlgorithmException {
- KeyGenerator secretGenerator=KeyGenerator.getInstance(ALGORITHM);
- SecureRandom secureRandom=new SecureRandom();
- secretGenerator.init(secureRandom);
- SecretKey secretKey=secretGenerator.generateKey();
- return secretKey;
- }
- final static String charsetName="UTF-8";
- static Charset charset=Charset.forName("UTF-8");
- //编码
- public static byte[] encrypt(String content,SecretKey secretKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
- byte[] encryptResult = aes(content.getBytes(charset),Cipher.ENCRYPT_MODE,secretKey);
- Encoder enc = Base64.getEncoder();
- String encStr = enc.encodeToString(encryptResult);
- System.out.println("加密后base64编码的密文 : " + encStr);
- return encryptResult;
- }
- //解码
- public static String decrypt(byte[] contentArray,SecretKey secretKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
- byte[] result=aes(contentArray,Cipher.DECRYPT_MODE,secretKey);
- return new String(result,charsetName);
- }
- private static byte[] aes(byte[] contentArray,int mode,SecretKey secretKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
- Cipher cipher=Cipher.getInstance(ALGORITHM);
- cipher.init(mode, secretKey);
- byte[] result=cipher.doFinal(contentArray);
- return result;
- }
- public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
- String content="不想写代码了";
- SecretKey secretKey=generatekey();
- byte[] encryptResult=encrypt(content,secretKey);
- String decryptResult=decrypt(encryptResult,secretKey);
- System.out.println("解密后的结果为:"+decryptResult);
- }
- }
复制代码
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
|