com.ironchain.common.kits.DigestKit.java Source code

Java tutorial

Introduction

Here is the source code for com.ironchain.common.kits.DigestKit.java

Source

/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.ironchain.common.kits;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
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.commons.lang3.Validate;

/**
 * ?SHA-1/MD5??.
 * 
 * ByteSource??Hex, Base64UrlSafeBase64
 * 
 * @author zheng xin
 */
public class DigestKit {

    private static final String SHA1 = "SHA-1";
    private static final String SHA256 = "SHA-256";
    private static final String MD5 = "MD5";

    private static final String AES = "AES";
    private static final String AES_CBC = "AES/CBC/PKCS5Padding";
    private static final String DES = "DES";
    private static final String DES_CBC = "DES/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();

    /**
     * sha1.
     */
    public static byte[] sha1(byte[] input) {
        return digest(input, SHA1, null, 1);
    }

    public static byte[] sha1(byte[] input, byte[] salt) {
        return digest(input, SHA1, salt, 1);
    }

    public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
        return digest(input, SHA1, salt, iterations);
    }

    /**
     * sha256.
     */
    public static byte[] sha256(byte[] input) {
        return digest(input, SHA256, null, 1);
    }

    public static byte[] sha256(byte[] input, byte[] salt) {
        return digest(input, SHA256, salt, 1);
    }

    public static byte[] sha256(byte[] input, byte[] salt, int iterations) {
        return digest(input, SHA256, salt, iterations);
    }

    /**
     * , ?md5sha1.
     */
    private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);

            if (salt != null) {
                digest.update(salt);
            }

            byte[] result = digest.digest(input);

            for (int i = 1; i < iterations; i++) {
                digest.reset();
                result = digest.digest(result);
            }
            return result;
        } catch (GeneralSecurityException e) {
            throw ExceptionKit.unchecked(e);
        }
    }

    /**
     * ??Byte[]salt.
     * 
     * @param numBytes
     *            byte?
     */
    public static byte[] generateSalt(int numBytes) {
        Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);

        byte[] bytes = new byte[numBytes];
        random.nextBytes(bytes);
        return bytes;
    }

    /**
     * md5.
     */
    public static byte[] md5(InputStream input) throws IOException {
        return digest(input, MD5);
    }

    /**
     * sha1.
     */
    public static byte[] sha1(InputStream input) throws IOException {
        return digest(input, SHA1);
    }

    private static byte[] digest(InputStream input, String algorithm) throws IOException {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            int bufferLength = 8 * 1024;
            byte[] buffer = new byte[bufferLength];
            int read = input.read(buffer, 0, bufferLength);

            while (read > -1) {
                messageDigest.update(buffer, 0, read);
                read = input.read(buffer, 0, bufferLength);
            }

            return messageDigest.digest();
        } catch (GeneralSecurityException e) {
            throw ExceptionKit.unchecked(e);
        }
    }

    // -- 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) {
            throw new RuntimeException(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?,
     * RFC2401160?(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) {
            throw new RuntimeException(e);
        }
    }

    // -- AES funciton --//
    /**
     * AES.
     * 
     * @param input
     *            
     * @param key
     *            ?AES?
     */
    public static byte[] aesEncrypt(byte[] input, byte[] key) {
        return cryptos(input, key, null, Cipher.ENCRYPT_MODE, AES, AES);
    }

    /**
     * AES.
     * 
     * @param input
     *            
     * @param key
     *            ?AES?
     */
    public static String aesEncrypt(String input, String key) {
        Charset charset = Charset.forName("UTF-8");
        return Base64.getEncoder().encodeToString(aesEncrypt(input.getBytes(charset), key.getBytes(charset)));
    }

    /**
     * AES.
     * 
     * @param input
     *            
     * @param key
     *            ?AES?
     * @param iv
     *            ???
     */
    public static byte[] aesEncrypt(byte[] input, byte[] key, byte[] iv) {
        return cryptos(input, key, iv, Cipher.ENCRYPT_MODE, AES, AES_CBC);
    }

    /**
     * AES, .
     * 
     * @param input
     *            Hex?
     * @param key
     *            ?AES?
     */
    public static byte[] aesDecrypt(byte[] input, byte[] key) {
        return cryptos(input, key, null, Cipher.DECRYPT_MODE, AES, AES);
    }

    /**
     * AES, .
     * 
     * @param input
     *            Hex?
     * @param key
     *            ?AES?
     */
    public static String aesDecrypt(String input, String key) {
        byte[] decryptResult = aesDecrypt(Base64.getDecoder().decode(input),
                key.getBytes(Charset.forName("UTF-8")));
        return new String(decryptResult, Charset.forName("UTF-8"));
    }

    /**
     * AES, .
     * 
     * @param input
     *            Hex?
     * @param key
     *            ?AES?
     * @param iv
     *            ???
     */
    public static byte[] aesDecrypt(byte[] input, byte[] key, byte[] iv) {
        return cryptos(input, key, iv, Cipher.DECRYPT_MODE, AES, AES_CBC);
    }

    /**
     * AES/DES?, ?.
     * 
     * @param input
     *            
     * @param key
     *            ?AES?
     * @param iv
     *            ???
     * @param mode
     *            Cipher.ENCRYPT_MODE  Cipher.DECRYPT_MODE
     * @param keyMode
     *            key?
     * @param encryptMode
     *            ?
     */
    private static byte[] cryptos(byte[] input, byte[] key, byte[] iv, int mode, String keyMode,
            String encryptMode) {
        try {
            SecretKey secretKey = new SecretKeySpec(key, keyMode);
            Cipher cipher = Cipher.getInstance(encryptMode);
            if (iv != null) {
                IvParameterSpec ivSpec = new IvParameterSpec(iv);
                cipher.init(mode, secretKey, ivSpec);
            } else {
                cipher.init(mode, secretKey);
            }
            return cipher.doFinal(input);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(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) {
            throw new RuntimeException(e);
        }
    }

    /**
     * ????,?cipher.getBlockSize(), 16.
     */
    public static byte[] generateIV() {
        byte[] bytes = new byte[DEFAULT_IVSIZE];
        random.nextBytes(bytes);
        return bytes;
    }

    // -- DES funciton --//
    /**
     * DES.
     * 
     * @param input
     *            
     * @param key
     *            ?AES?
     */
    public static byte[] desEncrypt(byte[] input, byte[] key) {
        return cryptos(input, key, null, Cipher.ENCRYPT_MODE, DES, DES);
    }

    /**
     * DES, .
     * 
     * @param input
     *            Hex?
     * @param key
     *            ?AES?
     */
    public static String desDecrypt(byte[] input, byte[] key) {
        byte[] decryptResult = cryptos(input, key, null, Cipher.DECRYPT_MODE, DES, DES);
        return new String(decryptResult, Charset.forName("UTF-8"));
    }

    /**
     * DES.
     * 
     * @param input
     *            
     * @param key
     *            ?AES?
     * @param iv
     *            ???
     */
    public static byte[] desEncrypt(byte[] input, byte[] key, byte[] iv) {
        return cryptos(input, key, iv, Cipher.ENCRYPT_MODE, DES, DES_CBC);
    }

    /**
     * DES, .
     * 
     * @param input
     *            Hex?
     * @param key
     *            ?AES?
     * @param iv
     *            ???
     */
    public static String desDecrypt(byte[] input, byte[] key, byte[] iv) {
        byte[] decryptResult = cryptos(input, iv, null, Cipher.DECRYPT_MODE, DES, DES_CBC);
        return new String(decryptResult, Charset.forName("UTF-8"));
    }

    /**
     * DES.
     * 
     * @param input
     *            
     * @param key
     *            ?AES?
     */
    public static String desEncrypt(String input, String key) {
        Charset charset = Charset.forName("UTF-8");
        return Base64.getEncoder().encodeToString(desEncrypt(input.getBytes(charset), key.getBytes(charset)));
    }

    /**
     * AES, .
     * 
     * @param input
     *            Hex?
     * @param key
     *            ?AES?
     */
    public static String desDecrypt(String input, String key) {
        return desDecrypt(Base64.getDecoder().decode(input), key.getBytes(Charset.forName("UTF-8")));
    }

}