21xrx.com
2025-04-01 23:45:42 Tuesday
文章检索 我的文章 写文章
Java加密解密工具类案例:实现AES加密和解密
2023-06-15 17:16:19 深夜i     17     0
Java加密解密 AES加密 AES解密

如果我们需要在Java中对敏感信息进行加密处理,那么就需要用到加密解密工具类了。本文将向您介绍如何使用Java实现AES加密和解密,并提供相应的代码案例。

一、AES加密解密简介

AES加密算法是目前最常用的对称加密算法之一,它采用128位、192位或256位密钥对数据进行加密和解密。因为密钥长度较长,所以安全性较高。在使用AES加密解密时,我们需要指定密钥。

二、实现AES加密和解密

下面是一个实现AES加密和解密的Java代码案例:

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtil {
    // 加密
    public static String encrypt(String sSrc, String sKey) throws Exception {
      if (sKey == null) {
        System.out.print("Key为空null");
        return null;
      }
      // 判断Key是否为16位
      if (sKey.length() != 16) {
        System.out.print("Key长度不是16位");
        return null;
      }
      byte[] raw = sKey.getBytes("utf-8");
      SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      // 使用CBC模式,需要一个向量iv,可增加加密算法的强度
      IvParameterSpec iv = new IvParameterSpec(sKey.getBytes("utf-8"));
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
      byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
      // 对加密后的结果进行Base64编码
      return Base64.getEncoder().encodeToString(encrypted);
    }
    // 解密
    public static String decrypt(String sSrc, String sKey) throws Exception {
      try {
        // 判断Key是否正确
        if (sKey == null) {
          System.out.print("Key为空null");
          return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
          System.out.print("Key长度不是16位");
          return null;
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(sKey.getBytes("utf-8"));
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        // 先对字符串进行Base64解码
        byte[] encrypted1 = Base64.getDecoder().decode(sSrc);
        try {
          byte[] original = cipher.doFinal(encrypted1);
          String originalString = new String(original, "utf-8");
          return originalString;
        } catch (Exception e) {
          System.out.println(e.toString());
          return null;
        }
      } catch (Exception ex) {
        System.out.println(ex.toString());
        return null;
      }
    }
  public static void main(String[] args) throws Exception {
    String sKey = "0123456789abcdef";
    String sSrc = "test";
    System.out.println("加密前的字符串:" + sSrc);
    String enString = encrypt(sSrc, sKey);
    System.out.println("加密后的字符串:" + enString);
    String deString = decrypt(enString, sKey);
    System.out.println("解密后的字符串:" + deString);
  }
}

在上面的代码中,我们定义了一个AESUtil类,其中包含了encrypt()方法和decrypt()方法,分别用于加密和解密操作。同时,我们还可以通过main()方法进行测试。

三、关键词

Java加密解密、AES加密、AES解密

  
  

评论区

    相似文章
请求出错了