package jwt_demo;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES";
private final static String charsetName = "UTF-8";
public static SecretKey generateKey() throws NoSuchAlgorithmException {
KeyGenerator secretGenerator = KeyGenerator.getInstance(ALGORITHM);
secretGenerator.init(256);
SecureRandom secureRandom = new SecureRandom();
secretGenerator.init(secureRandom);
return secretGenerator.generateKey();
}
private static byte[] saveSecretKey(SecretKey secretKey) {
Base64.Encoder en = Base64.getEncoder();
return en.encode(secretKey.getEncoded());
}
private static SecretKey getSavedSecretKey(byte[] key) {
Base64.Decoder de = Base64.getDecoder();
byte[] dekey = de.decode(key);
return new SecretKeySpec(dekey, ALGORITHM);
}
private static byte[] aes(byte[] contentArray, int mode, SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(mode, secretKey);
return cipher.doFinal(contentArray);
}
public static byte[] encrypt(String content, SecretKey secretKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
return encrypt(content.getBytes(), secretKey);
}
public static byte[] encrypt(byte[] content, SecretKey secretKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
return aes(content, Cipher.ENCRYPT_MODE, secretKey);
}
public static String decrypt(byte[] contentArray, SecretKey secretKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException {
byte[] result = aes(contentArray, Cipher.DECRYPT_MODE, secretKey);
return new String(result,
Java 安全
最新推荐文章于 2024-04-09 05:59:26 发布