AES加密算法工具类

AES属于对称加密算法,我们在开发api接口需要签名校验常常使用就是AES算法。说简单点就是通过算法以及你的参数得出你的sign 然后传到服务端,再根据你的参数生成一个sign 和你的sign 做比较。相等说明参数没问题。不想等校验失败。下面就将我自己的一个常用的一个AES加密算法工具类记录。

package com.netease.is.nc.sdk.utils;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 * @Title: AesUtil.java
 * @Package com.netease.is.nc.sdk.utils
 * @author Drj
 * @date 2018年6月7日 下午8:48:53
 * @version V1.0
 */
public class AesUtil {
    private static final String key = "dairuijie";// 加密用的Key 可以用26个字母和数字组成
    /**
     * 加密
     * @param cleartext
     * @param key
     * @return
     * @throws InvalidKeyException
     * @throws InvalidAlgorithmParameterException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     */
    public static String encrypt(String cleartext, String key)
            throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
            BadPaddingException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] keyBytes = new byte[16];
        byte[] b = key.getBytes("UTF-8");
        int len = b.length;

        if (len > keyBytes.length) {
            len = keyBytes.length;
        }
        System.arraycopy(b, 0, keyBytes, 0, len);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");

        IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
        cipher.init(1, keySpec, ivSpec);

        byte[] results = cipher.doFinal(cleartext.getBytes("UTF-8"));

        return toHex(results);
    }
    /**
     * 解密
     * @param encrypted
     * @param key
     * @return
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     * @throws InvalidAlgorithmParameterException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     */
    public static String decrypt(String encrypted, String key)
            throws UnsupportedEncodingException, InvalidKeyException, InvalidAlgorithmParameterException,
            IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] keyBytes = new byte[16];
        byte[] b = key.getBytes("UTF-8");
        int len = b.length;
        if (len > keyBytes.length) {
            len = keyBytes.length;
        }
        System.arraycopy(b, 0, keyBytes, 0, len);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
        cipher.init(2, keySpec, ivSpec);

        byte[] results = cipher.doFinal(toByte(encrypted));
        return new String(results, "UTF-8");
    }
    /**
     * 组合加密
     * @param buf
     * @return
     */
    private static String toHex(byte[] buf) {
        if (buf == null) {
            return "";
        }
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; ++i) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }
    /**
     * 解析加密串
     * @param hexString
     * @return
     */
    private static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;

        byte[] result = new byte[len];
        for (int i = 0; i < len; ++i) {
            String hexStringTemp = hexString.substring(2 * i, 2 * i + 2);
            result[i] = Integer.valueOf(hexStringTemp, 16).byteValue();
        }
        return result;
    }

    private static void appendHex(StringBuffer sb, byte b) {
        sb.append("0123456789ABCDEF".charAt(b >> 4 & 0xF)).append("0123456789ABCDEF".charAt(b & 0xF));
    }

    public static void main(String[] args) throws Exception {
        StringBuilder build = new StringBuilder();
        build.append("count").append("=").append(100).append("&").append("offset").append("=").append(2).append("&")
                .append("noticeType").append("=").append(1).toString();
        System.out.println(encrypt(build.toString(), key));
        System.out.println(decrypt("15305BD6A056759390F064413FA8099F274709BDAF7BE341D1A18EBAD3AC9E01",key));
    }
}

结果如图:


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是 Java 中使用 AES 加密解密的工具类,其中包括了 AES/CBC/PKCS5Padding 算法的加密解密方法: ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class AESUtil { private static final String ALGORITHM_AES = "AES"; private static final String CIPHER_AES_CBC_PKCS5PADDING = "AES/CBC/PKCS5Padding"; private static final String IV = "0123456789abcdef"; // 16 位 /** * AES 加密 * * @param data 需要加密的数据 * @param key 密钥字符串(16、24 或 32 位) * @return 加密后的字符串 */ public static String encryptByAES(String data, String key) { try { byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM_AES); Cipher cipher = Cipher.getInstance(CIPHER_AES_CBC_PKCS5PADDING); IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8)); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; } /** * AES 解密 * * @param data 需要解密的数据 * @param key 密钥字符串(16、24 或 32 位) * @return 解密后的字符串 */ public static String decryptByAES(String data, String key) { try { byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM_AES); Cipher cipher = Cipher.getInstance(CIPHER_AES_CBC_PKCS5PADDING); IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8)); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); byte[] encryptedBytes = Base64.getDecoder().decode(data); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); return new String(decryptedBytes, StandardCharsets.UTF_8); } catch (Exception e) { e.printStackTrace(); } return null; } } ``` 使用示例: ```java public static void main(String[] args) { String data = "Hello, world!"; String key = "1234567890123456"; String encryptedData = AESUtil.encryptByAES(data, key); System.out.println("加密后的数据:" + encryptedData); String decryptedData = AESUtil.decryptByAES(encryptedData, key); System.out.println("解密后的数据:" + decryptedData); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蜗牛乌龟一起走

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值