com.miyue.util.Cryptos.java Source code

Java tutorial

Introduction

Here is the source code for com.miyue.util.Cryptos.java

Source

/**
 * Copyright (c) 2005-2012 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.miyue.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
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.commons.io.FileUtils;

import com.miyue.exception.Exceptions;

/**
 * ?HMAC-SHA1??? ? DES/AES.
 * 
 * ?HexBase64???.
 * 
 * @author spring
 */
public class Cryptos {

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

    private Cryptos() {
    }

    //-- 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 Exceptions.unchecked(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 Exceptions.unchecked(e);
        }
    }

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

    /**
     * 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?
     */
    public static String aesDecrypt(byte[] input, byte[] key) {
        byte[] decryptResult = aes(input, key, Cipher.DECRYPT_MODE);
        return new String(decryptResult);
    }

    /**
     * AES, .
     * 
     * @param input Hex?
     * @param key ?AES?
     * @param iv ???
     */
    public static String aesDecrypt(byte[] input, byte[] key, byte[] iv) {
        byte[] decryptResult = aes(input, key, iv, Cipher.DECRYPT_MODE);
        return new String(decryptResult);
    }

    /**
     * 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) {
            throw Exceptions.unchecked(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) {
            throw Exceptions.unchecked(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 Exceptions.unchecked(e);
        }
    }

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

    public static void main(String[] args) throws Exception {
        String helloWorld = "skymobi-android-browser-statiscs-key";
        byte key[] = generateAesKey();
        File file = new File("/Users/feize/key");
        //      byte key[]=FileUtils.readFileToByteArray(file);
        FileUtils.writeByteArrayToFile(file, key);
        //[B@4139eeda
        System.out.println("key is:" + key);
        //      FileOutputStream fos = new FileOutputStream("/Users/feize/key"); 
        //      fos.write(key);
        byte encodeString[] = aesEncrypt(helloWorld.getBytes(), key);
        System.out.println("encodeString is:" + encodeString);
        String decodeString = aesDecrypt(encodeString, key);
        System.out.println("decodeString is:" + decodeString);
    }
}