天天看點

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));
    }
}
           

結果如圖:

AES加密算法工具類

繼續閱讀