AESUtil对称加密工具分享

2021-01-08 / 5 阅读 / Java
工具不依赖其他第三方工具包,可轻装引入
完整代码示例:
package ***.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

/**
 * AESUtil 对称加密和解密工具类.
 * <p>
 * 工具默认采用128位(16字节|32Hex字符)密钥
 *
 * @author wangbing
 * @version 0.0.1
 * @since 1.8
 */
public class AESUtil {

    private static final String ALGORITHM = "AES";
    private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";

    /**
     * 生成密钥对.
     */
    public static String generateDesKey() throws NoSuchAlgorithmException {
        //实例化
        KeyGenerator kgen = null;
        kgen = KeyGenerator.getInstance("AES");
        //设置密钥长度
        kgen.init(128);
        //生成密钥
        SecretKey skey = kgen.generateKey();
        //返回密钥的二进制编码
        return BytesUtil.bytes2Hex(skey.getEncoded());
    }

    /**
     * 加密并转为Base64字符
     */
    public static String encrypt2Base64(String data, String hexSecret) throws Exception {
        byte[] encrypt = encrypt(data, hexSecret);
        return Base64Util.encodeToString(encrypt);
    }

    /**
     * 加密并转为Base64字符
     */
    public static String encrypt2Base64(byte[] data, String hexSecret) throws Exception {
        byte[] encrypt = encrypt(data, hexSecret);
        return Base64Util.encodeToString(encrypt);
    }

    /**
     * 加密
     */
    public static byte[] encrypt(String data, String hexSecret) throws Exception {
        return encrypt(data.getBytes(), hexSecret);
    }

    /**
     * 加密
     */
    public static byte[] encrypt(byte[] data, String hexSecret) throws Exception {
        if (hexSecret.length() != 32) {
            throw new IllegalArgumentException("Hex secret's length must be 32");
        }
        return encrypt(data, BytesUtil.hex2Bytes(hexSecret));
    }

    /**
     * 保证加密情况无异常抛出
     */
    public static String encrypt2Base64Safe(String data, String hexSecret) {
        byte[] encrypt = new byte[0];
        try {
            encrypt = encrypt(data, hexSecret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Base64Util.encodeToString(encrypt);
    }

    /**
     * 保证加密情况无异常抛出
     */
    public static String encrypt2Base64Safe(byte[] data, String hexSecret) {
        byte[] encrypt = new byte[0];
        try {
            encrypt = encrypt(data, hexSecret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Base64Util.encodeToString(encrypt);
    }

    /**
     * 保证加密情况无异常抛出
     */
    public static byte[] encryptSafe(String data, String hexSecret) {
        try {
            return encrypt(data.getBytes(), hexSecret);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 保证加密情况无异常抛出
     */
    public static byte[] encryptSafe(byte[] data, String hexSecret) {
        if (hexSecret.length() != 32) {
            throw new IllegalArgumentException("Hex secret's length must be 32");
        }
        try {
            return encrypt(data, BytesUtil.hex2Bytes(hexSecret));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 加密.
     *
     * @param data   待加密字节数据
     * @param secret 安全密钥
     * @return 字节数组
     */
    public static byte[] encrypt(byte[] data, byte[] secret) throws Exception {
        if (secret == null || secret.length != 16) {
            throw new IllegalArgumentException("secret's length must be 16");
        }
        SecretKeySpec key = new SecretKeySpec(secret, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR); // 创建密码器
        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
        return cipher.doFinal(data);// 加密
    }

    public static String decrypt2String(String base64Data, String hexSecret) throws Exception {
        byte[] decrypt = decrypt(base64Data, hexSecret);
        return new String(decrypt);
    }

    public static byte[] decrypt(String base64Data, String hexSecret) throws Exception {
        return decrypt(Base64Util.decode(base64Data), BytesUtil.hex2Bytes(hexSecret));
    }

    public static byte[] decrypt(byte[] data, String hexSecret) throws Exception {
        return decrypt(data, BytesUtil.hex2Bytes(hexSecret));
    }

    /**
     * 解密.
     *
     * @param data   待解密字节数组
     * @param secret 密钥
     */
    public static byte[] decrypt(byte[] data, byte[] secret) throws Exception {
        if (secret == null || secret.length != 16) {
            throw new IllegalArgumentException("secret's length must be 16");
        }
        SecretKeySpec key = new SecretKeySpec(secret, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(data);
    }
}
相关推荐