整理utils中的类

This commit is contained in:
calvin.xiao
2016-12-29 15:40:16 +08:00
parent 0201d1229f
commit 492d5576de
19 changed files with 24 additions and 627 deletions
@@ -8,9 +8,7 @@ package org.springside.modules.utils;
import java.util.Date;
/**
* 日期提供者,使用它而不是直接取得系统时间,方便测试。
*
* @author calvin
* 日期提供者, 使用它而不是直接取得系统时间, 方便测试.
*/
public interface Clock {
@@ -1,195 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005, 2014 springside.github.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package org.springside.modules.utils;
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;
/**
* 支持HMAC-SHA1消息签名 及 DES/AES对称加密的工具类.
*
* 支持Hex与Base64两种编码方式.
*
* @author calvin
*/
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();
// -- 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算法对密钥无特殊要求, 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) {
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;
}
}
@@ -1,263 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005, 2014 springside.github.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package org.springside.modules.utils;
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.zip.CRC32;
import org.apache.commons.lang3.Validate;
import org.springside.modules.constants.Charsets;
import com.google.common.hash.Hashing;
/**
* 消息摘要的工具类.
*
* 支持SHA-1/MD5这些安全性较高,返回byte[]的(可用Encodes进一步被编码为Hex, Base64或UrlSafeBase64),支持带salt达到更高的安全性.
*
* 也支持crc32,murmur32这些不追求安全性,性能较高,返回int的.
*
* @author calvin
*/
public class Digests {
private static final String SHA1 = "SHA-1";
private static final String MD5 = "MD5";
private static SecureRandom random = new SecureRandom();
/**
* 对输入字符串进行sha1散列.
*/
public static byte[] sha1(byte[] input) {
return digest(input, SHA1, null, 1);
}
/**
* 对输入字符串进行sha1散列.
*/
public static byte[] sha1(String input) {
return digest(input.getBytes(Charsets.UTF8), SHA1, null, 1);
}
/**
* 对输入字符串进行sha1散列.
*/
public static byte[] sha1(String input, Charset charset) {
return digest(input.getBytes(charset), SHA1, null, 1);
}
/**
* 对输入字符串进行sha1散列,带salt达到更高的安全性.
*/
public static byte[] sha1(byte[] input, byte[] salt) {
return digest(input, SHA1, salt, 1);
}
/**
* 对输入字符串进行sha1散列,带salt达到更高的安全性.
*/
public static byte[] sha1(String input, byte[] salt) {
return digest(input.getBytes(Charsets.UTF8), SHA1, salt, 1);
}
/**
* 对输入字符串进行sha1散列,带salt达到更高的安全性.
*/
public static byte[] sha1(String input, Charset charset, byte[] salt) {
return digest(input.getBytes(charset), SHA1, salt, 1);
}
/**
* 对输入字符串进行sha1散列,带salt而且迭代达到更高更高的安全性.
*/
public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
return digest(input, SHA1, salt, iterations);
}
/**
* 对输入字符串进行sha1散列,带salt而且迭代达到更高更高的安全性.
*/
public static byte[] sha1(String input, byte[] salt, int iterations) {
return digest(input.getBytes(Charsets.UTF8), SHA1, salt, iterations);
}
/**
* 对输入字符串进行sha1散列,带salt而且迭代达到更高更高的安全性.
*/
public static byte[] sha1(String input, Charset charset, byte[] salt, int iterations) {
return digest(input.getBytes(charset), SHA1, salt, iterations);
}
/**
* 对字符串进行散列, 支持md5与sha1算法.
*/
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 Exceptions.unchecked(e);
}
}
/**
* 生成随机的Byte[]作为salt.
*
* @param numBytes salt数组的大小
*/
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 Exceptions.unchecked(e);
}
}
/**
* 对输入字符串进行crc32散列.
*/
public static int crc32(byte[] input) {
CRC32 crc32 = new CRC32();
crc32.update(input);
return (int) crc32.getValue();
}
/**
* 对输入字符串进行crc32散列.
*/
public static int crc32(String input) {
CRC32 crc32 = new CRC32();
crc32.update(input.getBytes(Charsets.UTF8));
return (int) crc32.getValue();
}
/**
* 对输入字符串进行crc32散列.
*/
public static int crc32(String input, Charset charset) {
CRC32 crc32 = new CRC32();
crc32.update(input.getBytes(charset));
return (int) crc32.getValue();
}
/**
* 对输入字符串进行crc32散列,与php兼容,在64bit系统下返回永远是正数的long
*/
public static long crc32AsLong(byte[] input) {
CRC32 crc32 = new CRC32();
crc32.update(input);
return crc32.getValue();
}
/**
* 对输入字符串进行crc32散列,与php兼容,在64bit系统下返回永远是正数的long
*/
public static long crc32AsLong(String input) {
CRC32 crc32 = new CRC32();
crc32.update(input.getBytes(Charsets.UTF8));
return crc32.getValue();
}
/**
* 对输入字符串进行crc32散列,与php兼容,在64bit系统下返回永远是正数的long
*/
public static long crc32AsLong(String input, Charset charset) {
CRC32 crc32 = new CRC32();
crc32.update(input.getBytes(charset));
return crc32.getValue();
}
/**
* 对输入字符串进行murmur32散列
*/
public static int murmur32(byte[] input) {
return Hashing.murmur3_32().hashBytes(input).asInt();
}
/**
* 对输入字符串进行murmur32散列
*/
public static int murmur32(String input) {
return Hashing.murmur3_32().hashString(input, Charsets.UTF8).asInt();
}
/**
* 对输入字符串进行murmur32散列
*/
public static int murmur32(String input, Charset charset) {
return Hashing.murmur3_32().hashString(input, charset).asInt();
}
/**
* 对输入字符串进行murmur32散列,带有seed
*/
public static int murmur32(byte[] input, int seed) {
return Hashing.murmur3_32(seed).hashBytes(input).asInt();
}
/**
* 对输入字符串进行murmur32散列,带有seed
*/
public static int murmur32(String input, int seed) {
return Hashing.murmur3_32(seed).hashString(input, Charsets.UTF8).asInt();
}
/**
* 对输入字符串进行murmur32散列,带有seed
*/
public static int murmur32(String input, Charset charset, int seed) {
return Hashing.murmur3_32(seed).hashString(input, charset).asInt();
}
}
@@ -21,8 +21,6 @@ import org.apache.commons.lang3.StringEscapeUtils;
* 2.自制的base62 编码
* 3.Commons-Lang的xml/html escape
* 4.JDK提供的URLEncoder
*
* @author calvin
*/
public class Encodes {
@@ -11,9 +11,7 @@ import java.io.StringWriter;
/**
* 关于异常的工具类.
*
* 参考了guava的Throwables。
*
* @author calvin
* 参考了guava的Throwables.
*/
public class Exceptions {
@@ -10,8 +10,6 @@ import java.util.UUID;
/**
* 封装各种生成唯一性ID算法的工具类.
*
* @author calvin
*/
public class Ids {
@@ -7,7 +7,6 @@ import com.google.common.primitives.Longs;
* 数字的工具类
*
* 1.基于Guava的原始类型与byte[]的转换.
*
*/
public class Numbers {
@@ -21,8 +21,6 @@ import org.slf4j.LoggerFactory;
* 反射工具类.
*
* 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
*
* @author calvin
*/
public class Reflections {
private static final String SETTER_PREFIX = "set";
@@ -16,8 +16,6 @@ package org.springside.modules.utils;
* StringBuilder sb = threadLocalStringBuilderHolder.get().resetAndGetStringBuilder();
*
* </pre>
*
* @author calvin
*
*/
public class StringBuilderHolder {
@@ -3,7 +3,7 @@
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package org.springside.modules.utils;
package org.springside.modules.utils.collection;
import java.util.ArrayList;
import java.util.Collection;
@@ -14,6 +14,7 @@ import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springside.modules.utils.Reflections;
import com.google.common.primitives.Doubles;
import com.google.common.primitives.Ints;
@@ -22,15 +23,15 @@ import com.google.common.primitives.Longs;
/**
* Collections工具集.
*
* 主要由三部分组成:
* 主要由几部分组成:
*
* 1. 是否Empty的最常用函数.
*
* 2. 支持以原始类型存储的List,节约存储空间, 基于Guava.
* 2. 支持转换原始类型数组为的原始类型数组的List,节约存储空间, 基于Guava.
*
* 2. 源自Apache Commons Collection, 争取不用在项目里引入它.
* 3. 源自Apache Commons Collection, 争取不用在项目里引入它.
*
* 3. 反射提取集合种元素及其属性的功能.
* 4. 反射提取集合种元素及其属性的功能.
*
* 在JDK的Collections和Guava的Collections2/Iterables后, 命名为Collections3.
*
@@ -1,4 +1,4 @@
package org.springside.modules.utils;
package org.springside.modules.utils.collection;
import java.util.AbstractSet;
import java.util.Collection;
@@ -1,14 +1,14 @@
package org.springside.modules.utils;
package org.springside.modules.utils.thread;
import java.util.HashMap;
import java.util.Map;
/**
* 存储于ThreadLocal的上下文信息.
* 存储于ThreadLocal的Map, 用于存储上下文.
*/
public class ThreadLocalContext {
private static ThreadLocal<Map<String, Object>> context = new ThreadLocal<Map<String, Object>>() {
private static ThreadLocal<Map<String, Object>> contextMap = new ThreadLocal<Map<String, Object>>() {
@Override
protected Map<String, Object> initialValue() {
return new HashMap<String, Object>();
@@ -16,24 +16,24 @@ public class ThreadLocalContext {
};
/**
* 放入ThreadLocal的Context.
* 放入ThreadLocal.
*/
public static void put(String key, Object value) {
context.get().put(key, value);
contextMap.get().put(key, value);
}
/**
* 取出ThreadLocal的Context.
* 取出ThreadLocal.
*/
@SuppressWarnings("unchecked")
public static <T> T get(String key) {
return (T) (context.get().get(key));
return (T) (contextMap.get().get(key));
}
/**
* 清理ThreadLocal的Context内容.
*/
public static void reset() {
context.get().clear();
contextMap.get().clear();
}
}
@@ -1,4 +1,4 @@
package org.springside.modules.utils;
package org.springside.modules.utils.thread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
@@ -3,7 +3,7 @@
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package org.springside.modules.utils;
package org.springside.modules.utils.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
@@ -17,8 +17,6 @@ import com.google.common.util.concurrent.ThreadFactoryBuilder;
/**
* 线程相关工具类.
*
* @author calvin
*/
public class Threads {
@@ -1,61 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005, 2014 springside.github.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package org.springside.modules.utils;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springside.modules.utils.Cryptos;
import org.springside.modules.utils.Encodes;
public class CryptosTest {
@Test
public void mac() {
String input = "foo message";
// key可为任意字符串
// byte[] key = "a foo key".getBytes();
byte[] key = Cryptos.generateHmacSha1Key();
assertThat(key).hasSize(20);
byte[] macResult = Cryptos.hmacSha1(input.getBytes(), key);
System.out.println("hmac-sha1 key in hex :" + Encodes.encodeHex(key));
System.out.println("hmac-sha1 in hex result :" + Encodes.encodeHex(macResult));
assertThat(Cryptos.isMacValid(macResult, input.getBytes(), key)).isTrue();
}
@Test
public void aes() {
byte[] key = Cryptos.generateAesKey();
assertThat(key).hasSize(16);
String input = "foo message";
byte[] encryptResult = Cryptos.aesEncrypt(input.getBytes(), key);
String descryptResult = Cryptos.aesDecrypt(encryptResult, key);
System.out.println("aes key in hex :" + Encodes.encodeHex(key));
System.out.println("aes encrypt in hex result :" + Encodes.encodeHex(encryptResult));
assertThat(descryptResult).isEqualTo(input);
}
@Test
public void aesWithIV() {
byte[] key = Cryptos.generateAesKey();
byte[] iv = Cryptos.generateIV();
assertThat(key).hasSize(16);
assertThat(iv).hasSize(16);
String input = "foo message";
byte[] encryptResult = Cryptos.aesEncrypt(input.getBytes(), key, iv);
String descryptResult = Cryptos.aesDecrypt(encryptResult, key, iv);
System.out.println("aes key in hex :" + Encodes.encodeHex(key));
System.out.println("iv in hex :" + Encodes.encodeHex(iv));
System.out.println("aes encrypt in hex result :" + Encodes.encodeHex(encryptResult));
assertThat(descryptResult).isEqualTo(input);
}
}
@@ -1,72 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005, 2014 springside.github.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package org.springside.modules.utils;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
public class DigestsTest {
@Test
public void digestString() {
String input = "user";
byte[] sha1Result = Digests.sha1(input.getBytes());
System.out.println("sha1 in hex result :" + Encodes.encodeHex(sha1Result));
byte[] salt = Digests.generateSalt(8);
System.out.println("salt in hex :" + Encodes.encodeHex(salt));
sha1Result = Digests.sha1(input.getBytes(), salt);
System.out.println("sha1 in hex result with salt :" + Encodes.encodeHex(sha1Result));
sha1Result = Digests.sha1(input.getBytes(), salt, 1024);
System.out.println("sha1 in hex result with salt and 1024 interations:" + Encodes.encodeHex(sha1Result));
}
@Test
public void digestFile() throws IOException {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("test.txt");
byte[] md5result = Digests.md5(is);
byte[] sha1result = Digests.sha1(is);
System.out.println("md5: " + Encodes.encodeHex(md5result));
System.out.println("sha1:" + Encodes.encodeHex(sha1result));
}
@Test
public void crc32String() {
String input = "user1";
int result = Digests.crc32(input);
System.out.println("crc32 for user1:" + result);
input = "user2";
result = Digests.crc32(input);
System.out.println("crc32 for user2:" + result);
}
@Test
public void murmurString() {
String input1 = "user1";
int result = Digests.murmur32(input1);
System.out.println("murmur32 for user1:" + result);
String input2 = "user2";
result = Digests.murmur32(input2);
System.out.println("murmur32 for user2:" + result);
int seed = (int) System.currentTimeMillis();
result = Digests.murmur32(input1, seed);
System.out.println("murmur32 with seed for user1:" + result);
result = Digests.murmur32(input2, seed);
System.out.println("murmur32 with seed for user2:" + result);
}
}
@@ -7,7 +7,7 @@ package org.springside.modules.utils;
import org.junit.Test;
public class IdentitiesTest {
public class IdsTest {
@Test
public void demo() {
@@ -3,13 +3,14 @@
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package org.springside.modules.utils;
package org.springside.modules.utils.collection;
import static org.assertj.core.api.Assertions.*;
import java.util.List;
import org.junit.Test;
import org.springside.modules.utils.collection.Collections3;
import com.google.common.collect.Lists;
@@ -3,7 +3,7 @@
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package org.springside.modules.utils;
package org.springside.modules.utils.thread;
import static org.assertj.core.api.Assertions.*;
@@ -16,6 +16,7 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springside.modules.test.log.LogbackListAppender;
import org.springside.modules.utils.thread.Threads;
public class ThreadsTest {