SecurityUtils

/**
*
*/
package com.paic.icore.acss.util;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

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

import com.paic.icore.acss.util.constants.ConstantsForEncoding;

/**
* @author ZENGXIANGCAI926
* 2014年3月27日 下午9:31:07
* 加密工具类
*/
public class SecurityUtil {
    private static final String ALGORITHM_AES = "AES"; // 使用AES加密
    private static final int DIGIT_AES = 128; // AES加密位数
    private static final String RNG = "SHA1PRNG"; // 随机数生成算法

    /**
     * AES加密
     * @param content
     * @param key
     */
    public static byte[] encryptCodeByAES(byte[] content, String key) {
        if (content == null || key == null) {
            return null;
        }
        return disposalCodeByAES(content, key, Cipher.ENCRYPT_MODE);
    }

    /**
     * AES解密
     * @param content
     * @param key
     * @throws UnsupportedEncodingException
     */
    public static byte[] decryptCodeByAES(byte[] content, String key) throws UnsupportedEncodingException {
        if (content == null || key == null) {
            return null;
        }
        return disposalCodeByAES(hex2byte(content), key, Cipher.DECRYPT_MODE);
    }

    /**
     * AES加密
     * 返回十六进制字符串
     * @param content
     * @param key
     */
    public static String encapEncryptCodeByAES(byte[] content, String key) {
        return binaryArrayToHexString(encryptCodeByAES(content, key));
    }

    /**
     * 转换为十六进制字符串
     * @param arr
     */
    public static String binaryArrayToHexString(byte[] arr) {
        if (arr == null || arr.length == 0) {
            return null;
        }
        StringBuffer pool = new StringBuffer();
        String hexString;
        for (byte a : arr) {
            hexString = Integer.toHexString(a & 0xFF);
            if (hexString.length() == 1) {
                pool.append("0");
            }
            pool.append(hexString);
        }
        return pool.toString().toUpperCase();
    }

    /**
     * @author EX-ZHUYU001
     * @param b
     * @return
     * @throws UnsupportedEncodingException
     */
    public static byte[] hex2byte(byte[] content) throws UnsupportedEncodingException {
        if ((content.length % 2) != 0)
            throw new IllegalArgumentException("长度不是偶数");

        byte[] byteContent = new byte[content.length / 2];

        for (int n = 0; n < content.length; n += 2) {
            String item = null;
            item = new String(content, n, 2, ConstantsForEncoding.UTF8_ENCODING);
            byteContent[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return byteContent;
    }

    /**
     * AES处理byte数组
     * @param specalStr
     * @param mode
     */
    private static byte[] disposalCodeByAES(byte[] content, String specalStr, int mode) {
        try {
            KeyGenerator key = KeyGenerator.getInstance(ALGORITHM_AES);
            SecureRandom srandom = SecureRandom.getInstance(RNG);
            srandom.setSeed(specalStr.getBytes(ConstantsForEncoding.UTF8_ENCODING));
            key.init(DIGIT_AES, srandom);
            SecretKeySpec specKey = new SecretKeySpec(key.generateKey().getEncoded(), ALGORITHM_AES);
            Cipher cipher = Cipher.getInstance(ALGORITHM_AES);
            cipher.init(mode, specKey);
            return cipher.doFinal(content);
        } catch (Exception e) {
            LogUtils.error("SecurityUtil disposalCodeByAES 加密失败:" + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 使用SHA1PRNG算法加密
     *
     * @param content
     * @param password
     * @return
     * @throws Exception
     */
    public static String encryptSha1prng(String content, String password) throws Exception {
        if (content == null || "".equals(content)) {
            throw new Exception("加密内容不能为空");
        }
        if (password == null || "".equals(password)) {
            throw new Exception("加密密钥不能为空");
        }
        // AES加密
        KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM_AES);
        SecureRandom sr = SecureRandom.getInstance(RNG);
        sr.setSeed(password.getBytes(ConstantsForEncoding.UTF8_ENCODING));
        kgen.init(128, sr);
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM_AES);
        Cipher cipher = Cipher.getInstance(ALGORITHM_AES);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        // 加密
        byte[] encoded = cipher.doFinal(content.getBytes(ConstantsForEncoding.UTF8_ENCODING));
        return parseByte2HexStr(encoded);
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    public static String asHex(byte buf[]) {
        StringBuffer strbuf = new StringBuffer(buf.length * 2);
        int i;
        for (i = 0; i < buf.length; i++) {
            if (((int) buf[i] & 0xff) < 0x10)
                strbuf.append("0");
            strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
        }
        return strbuf.toString();
    }

}

猜你喜欢

转载自licongming163.iteye.com/blog/2147580