add AES in Encryptor and Decryptor

This commit is contained in:
Timi
2025-10-30 16:47:55 +08:00
parent 9e6b97632a
commit 4a633765e8
2 changed files with 115 additions and 0 deletions

View File

@ -0,0 +1,65 @@
package com.imyeyu.utils;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* @author 夜雨
* @since 2025-10-29 16:02
*/
public class Encryptor {
public byte[] aesKey() {
return aesKey(256);
}
public byte[] aesKey(int size) {
try {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(size);
return keyGen.generateKey().getEncoded();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("not support AES encrypt");
}
}
/**
* 加密字符串
*
* @param data 待加密字符串
* @param key 密钥
* @return 加密结果
*/
public byte[] aes(String data, byte[] key) {
return aes(data.getBytes(), key);
}
/**
* 加密
*
* @param data 待加密字节数据
* @param key 密钥
* @return 加密结果
*/
public byte[] aes(byte[] data, byte[] key) {
try {
SecretKey secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(data);
} catch (IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e) {
throw new RuntimeException("invalid data");
} catch (InvalidKeyException e) {
throw new RuntimeException("invalid key");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("not support AES encrypt");
}
}
}