66 lines
1.6 KiB
Java
66 lines
1.6 KiB
Java
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");
|
|
}
|
|
}
|
|
}
|