Java使用AES加密解密

AES加密机制:

密码学中的高级加密标准(Advanced Encryption Standard,AES),又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。

这个标准用来替代原先的 DES(Data Encryption Standard),已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院 (NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一  [1]  。
该算法为比利时密码学家Joan Daemen和Vincent Rijmen所设计,结合两位作者的名字,以Rijdael之名命之,投稿高级加密标准的甄选流程。(Rijdael的发音近于 "Rhine doll"。)

 加密工具类:

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.log4j.Logger;
/**
 * @包名 com.energy.util
 * @创建人 jiangwenzhang
 * @日期 2018/6/8 0008
 * @时间 8:36
 * @描述
 */

/**
 * 支持HMAC-SHA1消息签名 及 DES/AES对称加密的工具类.
 *
 * 支持Hex与Base64两种编码方式.
 *
 */
public class Cryptos {
    private static Logger logger = Logger.getLogger(Cryptos.class);
    /**
     * 自定义密钥
     */
    private String strDefaultKey = "1865338218031218";
    private byte[] key = strDefaultKey.getBytes();

    private static final String AES = "AES";
    private static final String AES_CBC = "AES/CBC/PKCS5Padding";
    private static final String HMACSHA1 = "HmacSHA1";

    private static final int DEFAULT_HMACSHA1_KEYSIZE = 160; //RFC2401
    private static final int DEFAULT_AES_KEYSIZE = 128;
    private static final int DEFAULT_IVSIZE = 16;

    private static SecureRandom random = new SecureRandom();

    public Cryptos(){
    }
    public Cryptos(String strDefaultKey){
        this.strDefaultKey = strDefaultKey;
        this.key = strDefaultKey.getBytes();
    }

    //-- HMAC-SHA1 funciton --//
    /**
     * 使用HMAC-SHA1进行消息签名, 返回字节数组,长度为20字节.
     *
     * @param input 原始输入字符数组
     * @param key HMAC-SHA1密钥
     */
    public static byte[] hmacSha1(byte[] input, byte[] key) {
        try {
            SecretKey secretKey = new SecretKeySpec(key, HMACSHA1);
            Mac mac = Mac.getInstance(HMACSHA1);
            mac.init(secretKey);
            return mac.doFinal(input);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
            throw new CryptException("使用HMAC-SHA1进行消息签名出错:",e);
        }
    }

    /**
     * 校验HMAC-SHA1签名是否正确.
     *
     * @param expected 已存在的签名
     * @param input 原始输入字符串
     * @param key 密钥
     */
    public static boolean isMacValid(byte[] expected, byte[] input, byte[] key) {
        byte[] actual = hmacSha1(input, key);
        return Arrays.equals(expected, actual);
    }

    /**
     * 生成HMAC-SHA1密钥,返回字节数组,长度为160位(20字节).
     * HMAC-SHA1算法对密钥无特殊要求, RFC2401建议最少长度为160位(20字节).
     */
    public static byte[] generateHmacSha1Key() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(HMACSHA1);
            keyGenerator.init(DEFAULT_HMACSHA1_KEYSIZE);
            SecretKey secretKey = keyGenerator.generateKey();
            return secretKey.getEncoded();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
            throw new CryptException("生成HMAC-SHA1密钥出错:",e);
        }
    }

    //-- AES funciton --//
    /**
     * 使用AES加密原始字符串.
     *
     * @param input 原始输入字符数组
     * @param key 符合AES要求的密钥
     */
    public byte[] aesEncrypt(byte[] input) {
        if (key.length != 16) {
            logger.info("Key长度不是16位");
        }

        return aes(input, key, Cipher.ENCRYPT_MODE);
    }

    /**
     * 使用AES加密原始字符串.
     *
     * @param input 原始输入字符串
     */
    public String aesEncrypt(String input) {
        try{
            byte[] encryptResult = aesEncrypt(input.getBytes());
            return Encodes.encodeHex(encryptResult);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CryptException("生成HMAC-SHA1密钥出错:",e);
        }
    }

    /**
     * 使用AES加密原始字符串
     * @param input 原始输入字符数组
     * @param key 符合AES要求的密钥
     * @param iv 初始向量
     */
    public static byte[] aesEncrypt(byte[] input, byte[] key, byte[] iv) {
        return aes(input, key, iv, Cipher.ENCRYPT_MODE);
    }

    /**
     * 使用AES解密字符串, 返回原始字符串.
     *
     * @param input Hex编码的加密字符串
     * @param key 符合AES要求的密钥
     * @throws UnsupportedEncodingException
     */
    public String aesDecrypt(byte[] input) throws UnsupportedEncodingException {
        if (key.length != 16) {
            logger.info("Key长度不是16位");
        }
        byte[] decryptResult = aes(input, key, Cipher.DECRYPT_MODE);
        //return new String(decryptResult);
        return new String(decryptResult,"utf-8");
    }

    /**
     * 使用AES解密字符串, 返回原始字符串.
     *
     * @param input Hex编码的加密字符串
     * @throws UnsupportedEncodingException
     */
    public String aesDecrypt(String input) {
        try{
            return aesDecrypt(Encodes.decodeHex(input));
        } catch (Exception e) {
            e.printStackTrace();
            throw new CryptException("解密出错:",e);
        }
    }

    /**
     * 使用AES解密字符串, 返回原始字符串.
     * @param input Hex编码的加密字符串
     * @param key 符合AES要求的密钥
     * @param iv 初始向量
     * @throws UnsupportedEncodingException
     */
    public static String aesDecrypt(byte[] input, byte[] key, byte[] iv) throws UnsupportedEncodingException {
        byte[] decryptResult = aes(input, key, iv, Cipher.DECRYPT_MODE);
        return new String(decryptResult,"utf-8");
    }

    /**
     * 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
     *
     * @param input 原始字节数组
     * @param key 符合AES要求的密钥
     * @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
     */
    private static byte[] aes(byte[] input, byte[] key, int mode) {
        try {
            SecretKey secretKey = new SecretKeySpec(key, AES);
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(mode, secretKey);
            return cipher.doFinal(input);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
            throw new CryptException("使用AES加密或解密无编码的原始字节数组出错:",e);
        }
    }

    /**
     * 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
     *
     * @param input 原始字节数组
     * @param key 符合AES要求的密钥
     * @param iv 初始向量
     * @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
     */
    private static byte[] aes(byte[] input, byte[] key, byte[] iv, int mode) {
        try {
            SecretKey secretKey = new SecretKeySpec(key, AES);
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            Cipher cipher = Cipher.getInstance(AES_CBC);
            cipher.init(mode, secretKey, ivSpec);
            return cipher.doFinal(input);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
            throw new CryptException("使用AES加密或解密无编码的原始字节数组:",e);
        }
    }

    /**
     * 生成AES密钥,返回字节数组, 默认长度为128位(16字节).
     */
    public static byte[] generateAesKey() {
        return generateAesKey(DEFAULT_AES_KEYSIZE);
    }

    /**
     * 生成AES密钥,可选长度为128,192,256位.
     */
    public static byte[] generateAesKey(int keysize) {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
            keyGenerator.init(keysize);
            SecretKey secretKey = keyGenerator.generateKey();
            return secretKey.getEncoded();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
            throw new CryptException("生成AES密钥出错:",e);
        }
    }

    /**
     * 生成随机向量,默认大小为cipher.getBlockSize(), 16字节.
     */
    public static byte[] generateIV() {
        byte[] bytes = new byte[DEFAULT_IVSIZE];
        random.nextBytes(bytes);
        return bytes;
    }

    public byte[] getKey() {
        return key;
    }
    public void setKey(byte[] key) {
        this.key = key;
    }
}

自定义异常类:

/**
 * @包名 com.energy.util.AES
 * @创建人 jiangwenzhang
 * @日期 2018/6/8 0008
 * @时间 8:50
 * @描述
 */

/**
 *  自定义加密解密时产生的异常类
 */
public class CryptException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public CryptException() {
    }

    public CryptException(String msg, Throwable e) {
        super(msg, e);
    }

    public CryptException(String msg) {
        super(msg);
    }

    public CryptException(Throwable cause) {
        super(cause);
    }
}

封装各种格式的编码解码工具类:

import java.io.UnsupportedEncodingException;  
import java.net.URLDecoder;  
import java.net.URLEncoder;  
  
import org.apache.commons.codec.DecoderException;  
import org.apache.commons.codec.binary.Base64;  
import org.apache.commons.codec.binary.Hex;  
  
/** 
 * 封装各种格式的编码解码工具类. 
 *  
 * 1.Commons-Codec的 hex/base64 编码 
 * 2.自定义的base62 编码 
 * 3.Commons-Lang的xml/html escape 
 * 4.JDK提供的URLEncoder 
 *  
 */  
public class Encodes {  
  
    private static final String DEFAULT_URL_ENCODING = "UTF-8";  
    private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();  
  
    /** 
     * Hex编码. 
     */  
    public static String encodeHex(byte[] input) {  
        return Hex.encodeHexString(input);  
    }  
  
    /** 
     * Hex解码. 
     */  
    public static byte[] decodeHex(String input) {  
        try {  
            return Hex.decodeHex(input.toCharArray());  
        } catch (DecoderException e) {  
            throw new CryptException("Hex解码出错:", e);  
        }  
    }  
  
    /** 
     * Base64编码. 
     */  
    public static String encodeBase64(byte[] input) {  
        return Base64.encodeBase64String(input);  
    }  
  
    /** 
     * Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548). 
     */  
    public static String encodeUrlSafeBase64(byte[] input) {  
        return Base64.encodeBase64URLSafeString(input);  
    }  
  
    /** 
     * Base64解码. 
     */  
    public static byte[] decodeBase64(String input) {  
        return Base64.decodeBase64(input);  
    }  
  
    /** 
     * Base62编码。 
     */  
    public static String encodeBase62(byte[] input) {  
        char[] chars = new char[input.length];  
        for (int i = 0; i < input.length; i++) {  
            chars[i] = BASE62[((input[i] & 0xFF) % BASE62.length)];  
        }  
        return new String(chars);  
    }  
  
    /** 
     * URL 编码, Encode默认为UTF-8.  
     */  
    public static String urlEncode(String part) {  
        try {  
            return URLEncoder.encode(part, DEFAULT_URL_ENCODING);  
        } catch (UnsupportedEncodingException e) {  
            throw new CryptException("URL 编码出错:", e);  
        }  
    }  
  
    /** 
     * URL 解码, Encode默认为UTF-8.  
     */  
    public static String urlDecode(String part) {  
  
        try {  
            return URLDecoder.decode(part, DEFAULT_URL_ENCODING);  
        } catch (UnsupportedEncodingException e) {  
            throw new CryptException("URL 解码出错:", e);  
        }  
    }  
 

猜你喜欢

转载自www.cnblogs.com/jiangwz/p/9156633.html