#525 加强Utils Modules模块 傍晚成果,复活加密模块,添加Sampler,
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
package org.springside.modules.utils.base;
|
||||
|
||||
public class BooleanUtil {
|
||||
|
||||
public static Boolean toBooleanObject(String str, Boolean defaultValue) {
|
||||
if (str == null) {
|
||||
return defaultValue;
|
||||
} else {
|
||||
return Boolean.valueOf(str);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -21,11 +21,13 @@ import org.springside.modules.utils.number.NumberUtil;
|
||||
*
|
||||
* 2. 简单的合并系统变量(-D),环境变量 和默认值,以系统变量优先,在未引入Commons Config时使用.
|
||||
*
|
||||
* 3. Properties 本质上是一个HashTable,每次读写都会加锁,所以不支持频繁的System.getProperty(name)来检查系统内容变化 因此扩展了一个ListenableProperties,
|
||||
* 在其所关心的属性变化时进行通知.
|
||||
* 3. 统一读取Properties
|
||||
*
|
||||
* 4. 从文件或字符串装载Properties
|
||||
*
|
||||
* 5. Properties 本质上是一个HashTable,每次读写都会加锁,所以不支持频繁的System.getProperty(name)来检查系统内容变化 因此扩展了一个ListenableProperties,
|
||||
* 在其所关心的属性变化时进行通知.
|
||||
*
|
||||
* @author calvin
|
||||
*/
|
||||
public abstract class PropertiesUtil {
|
||||
@@ -177,23 +179,38 @@ public abstract class PropertiesUtil {
|
||||
*/
|
||||
public static Boolean booleanSystemProperty(String propertyName, String envName, Boolean defaultValue) {
|
||||
checkEnvName(envName);
|
||||
Boolean propertyValue = toBooleanObject(System.getProperty(propertyName));
|
||||
Boolean propertyValue = BooleanUtil.toBooleanObject(System.getProperty(propertyName), null);
|
||||
if (propertyValue != null) {
|
||||
return propertyValue;
|
||||
} else {
|
||||
propertyValue = toBooleanObject(System.getenv(envName));
|
||||
propertyValue = BooleanUtil.toBooleanObject(System.getenv(envName), null);
|
||||
return propertyValue != null ? propertyValue : defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
private static Boolean toBooleanObject(String str) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
} else {
|
||||
return Boolean.valueOf(str);
|
||||
}
|
||||
/////////////////// 读取Properties ////////////////////
|
||||
|
||||
public static Boolean getBoolean(Properties p, String name, Boolean defaultValue) {
|
||||
return BooleanUtil.toBooleanObject(p.getProperty(name), defaultValue);
|
||||
}
|
||||
|
||||
public static Integer getInt(Properties p, String name, Integer defaultValue) {
|
||||
return NumberUtil.toIntObject(p.getProperty(name), defaultValue);
|
||||
}
|
||||
|
||||
public static Long getLong(Properties p, String name, Long defaultValue) {
|
||||
return NumberUtil.toLongObject(p.getProperty(name), defaultValue);
|
||||
}
|
||||
|
||||
public static Double getDouble(Properties p, String name, Double defaultValue) {
|
||||
return NumberUtil.toDoubleObject(p.getProperty(name), defaultValue);
|
||||
}
|
||||
|
||||
public static String getString(Properties p, String name, String defaultValue) {
|
||||
return p.getProperty(name, defaultValue);
|
||||
}
|
||||
|
||||
/////////// 加载Properties////////
|
||||
/**
|
||||
* 检查环境变量名不能有'.',在linux下不支持
|
||||
*/
|
||||
|
||||
+12
@@ -4,6 +4,7 @@ import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
|
||||
import org.springside.modules.utils.concurrent.jsr166e.LongAdder;
|
||||
import org.springside.modules.utils.misc.Sampler;
|
||||
|
||||
import com.google.common.util.concurrent.RateLimiter;
|
||||
|
||||
@@ -34,8 +35,19 @@ public class ConcurrentTools {
|
||||
|
||||
/**
|
||||
* 返回漏桶算法的RateLimiter
|
||||
*
|
||||
* @permitsPerSecond 期望的QPS, RateLimiter将QPS平滑到毫秒级别上,但有蓄水及桶外预借的能力.
|
||||
*/
|
||||
public static RateLimiter rateLimiter(int permitsPerSecond) {
|
||||
return RateLimiter.create(permitsPerSecond);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回采样器.
|
||||
*
|
||||
* @param selectPercent 采样率,在0-100 之间,可以有小数位
|
||||
*/
|
||||
public static Sampler sampler(double selectPercent){
|
||||
return Sampler.create(selectPercent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package org.springside.modules.utils.misc;
|
||||
|
||||
import org.apache.commons.lang3.Validate;
|
||||
import org.springside.modules.utils.number.RandomUtil;
|
||||
|
||||
/**
|
||||
* 采样器
|
||||
*
|
||||
* from Twitter Common, 优化使用ThreadLocalRandom
|
||||
*
|
||||
* @author calvin
|
||||
*/
|
||||
public class Sampler {
|
||||
|
||||
private double threshold;
|
||||
|
||||
/**
|
||||
* 优化的创建函数,如果为0或100时,返回更直接的采样器
|
||||
*/
|
||||
public static Sampler create(double selectPercent) {
|
||||
if (selectPercent == 100) {
|
||||
return new AlwaysSampler();
|
||||
} else if (selectPercent == 0) {
|
||||
return new NeverSampler();
|
||||
} else {
|
||||
return new Sampler(selectPercent);
|
||||
}
|
||||
}
|
||||
|
||||
protected Sampler() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param selectPercent 采样率,在0-100 之间,可以有小数位
|
||||
*/
|
||||
public Sampler(double selectPercent) {
|
||||
Validate.isTrue((selectPercent >= 0) && (selectPercent <= 100),
|
||||
"Invalid selectPercent value: " + selectPercent);
|
||||
|
||||
this.threshold = selectPercent / 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前请求是否命中采样
|
||||
*/
|
||||
public boolean select() {
|
||||
return RandomUtil.threadLocalRandom().nextDouble() < threshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* 采样率为100时,总是返回true
|
||||
*/
|
||||
public static class AlwaysSampler extends Sampler {
|
||||
|
||||
public AlwaysSampler() {
|
||||
}
|
||||
|
||||
public boolean select() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 采样率为0时,总是返回false
|
||||
*/
|
||||
public static class NeverSampler extends Sampler {
|
||||
public boolean select() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@ public abstract class RandomUtil {
|
||||
*
|
||||
* 详见:《SecureRandom的江湖偏方与真实效果》http://calvin1978.blogcn.com/articles/securerandom.html
|
||||
*/
|
||||
public static Random secureRandom() {
|
||||
public static SecureRandom secureRandom() {
|
||||
try {
|
||||
return SecureRandom.getInstance("SHA1PRNG");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2005, 2014 springside.github.io
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
*******************************************************************************/
|
||||
package org.springside.modules.utils.security;
|
||||
|
||||
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.springside.modules.utils.base.ExceptionUtil;
|
||||
import org.springside.modules.utils.number.RandomUtil;
|
||||
|
||||
/**
|
||||
* 支持HMAC-SHA1消息签名 及 DES/AES对称加密的工具类.
|
||||
*
|
||||
* 支持Hex与Base64两种编码方式.
|
||||
*
|
||||
* @author calvin
|
||||
*/
|
||||
public class CryptoUtil {
|
||||
|
||||
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 = RandomUtil.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 ExceptionUtil.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 ExceptionUtil.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 ExceptionUtil.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 ExceptionUtil.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 ExceptionUtil.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机向量,默认大小为cipher.getBlockSize(), 16字节.
|
||||
*/
|
||||
public static byte[] generateIV() {
|
||||
byte[] bytes = new byte[DEFAULT_IVSIZE];
|
||||
random.nextBytes(bytes);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package org.springside.modules.utils.misc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springside.modules.utils.misc.Sampler.AlwaysSampler;
|
||||
import org.springside.modules.utils.misc.Sampler.NeverSampler;
|
||||
|
||||
public class SamplerTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
Sampler sampler = Sampler.create(10.5);
|
||||
int hits = 0;
|
||||
for (int i = 0; i < 10000; i++) {
|
||||
if (sampler.select()) {
|
||||
hits++;
|
||||
}
|
||||
}
|
||||
System.out.println("sample 10.5% in 10000 hits should close to 1050, actual is " + hits);
|
||||
|
||||
assertThat(hits).isBetween(900, 1200);
|
||||
//////////
|
||||
Sampler sampler2 = new Sampler(0.5);
|
||||
|
||||
hits = 0;
|
||||
for (int i = 0; i < 10000; i++) {
|
||||
if (sampler2.select()) {
|
||||
hits++;
|
||||
}
|
||||
}
|
||||
System.out.println("sample 0.5% in 10000 hits should close to 50, actual is " + hits);
|
||||
assertThat(hits).isBetween(20, 100);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void always(){
|
||||
Sampler sampler = Sampler.create(0d);
|
||||
assertThat(sampler).isInstanceOf(NeverSampler.class);
|
||||
sampler = Sampler.create(100);
|
||||
assertThat(sampler).isInstanceOf(AlwaysSampler.class);
|
||||
|
||||
try{
|
||||
sampler = Sampler.create(101);
|
||||
fail("shoud fail before");
|
||||
}catch(Exception e){
|
||||
assertThat(e).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
try{
|
||||
sampler = Sampler.create(-2.2);
|
||||
fail("shoud fail before");
|
||||
}catch(Exception e){
|
||||
assertThat(e).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2005, 2014 springside.github.io
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
*******************************************************************************/
|
||||
package org.springside.modules.utils.security;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springside.modules.utils.text.EncodeUtil;
|
||||
|
||||
|
||||
public class CryptoUtilTest {
|
||||
@Test
|
||||
public void mac() {
|
||||
String input = "foo message";
|
||||
|
||||
// key可为任意字符串
|
||||
// byte[] key = "a foo key".getBytes();
|
||||
byte[] key = CryptoUtil.generateHmacSha1Key();
|
||||
assertThat(key).hasSize(20);
|
||||
|
||||
byte[] macResult = CryptoUtil.hmacSha1(input.getBytes(), key);
|
||||
System.out.println("hmac-sha1 key in hex :" + EncodeUtil.encodeHex(key));
|
||||
System.out.println("hmac-sha1 in hex result :" + EncodeUtil.encodeHex(macResult));
|
||||
|
||||
assertThat(CryptoUtil.isMacValid(macResult, input.getBytes(), key)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aes() {
|
||||
byte[] key = CryptoUtil.generateAesKey();
|
||||
assertThat(key).hasSize(16);
|
||||
String input = "foo message";
|
||||
|
||||
byte[] encryptResult = CryptoUtil.aesEncrypt(input.getBytes(), key);
|
||||
String descryptResult = CryptoUtil.aesDecrypt(encryptResult, key);
|
||||
|
||||
System.out.println("aes key in hex :" + EncodeUtil.encodeHex(key));
|
||||
System.out.println("aes encrypt in hex result :" + EncodeUtil.encodeHex(encryptResult));
|
||||
assertThat(descryptResult).isEqualTo(input);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aesWithIV() {
|
||||
byte[] key = CryptoUtil.generateAesKey();
|
||||
byte[] iv = CryptoUtil.generateIV();
|
||||
assertThat(key).hasSize(16);
|
||||
assertThat(iv).hasSize(16);
|
||||
String input = "foo message";
|
||||
|
||||
byte[] encryptResult = CryptoUtil.aesEncrypt(input.getBytes(), key, iv);
|
||||
String descryptResult = CryptoUtil.aesDecrypt(encryptResult, key, iv);
|
||||
|
||||
System.out.println("aes key in hex :" + EncodeUtil.encodeHex(key));
|
||||
System.out.println("iv in hex :" + EncodeUtil.encodeHex(iv));
|
||||
System.out.println("aes encrypt in hex result :" + EncodeUtil.encodeHex(encryptResult));
|
||||
assertThat(descryptResult).isEqualTo(input);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user