Java 安全

本文详细探讨了Java的安全模型,包括沙箱环境、类加载器、权限管理以及如何防止常见的安全漏洞。通过实例分析,解释了如何在Java应用程序中实现安全控制,确保代码和数据的安全。
摘要由CSDN通过智能技术生成
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,
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值