5
Crypto
Calvin edited this page 2013-11-14 01:37:15 +08:00
This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

##Overview 因为Java的Crypto API始终有点难用SpringSide在core module中的org.springside.modules.security.utils中提供了封装。
API的出入参数都是byte[]数组需要配合Encodes来转换成Hex或Base64存储。

##Digests消息摘要 去年一轮的密码被盗风波后使用salt并迭代N次的sha-1式密码存储已经是标配了。
使用随机salt是避免相同的密码的sha-1值相同还是容易被穷举的猜到。
而迭代N次纯粹是加大暴力破解的难度。

因此针对字符串消息摘要API如下

public static byte[] sha1(String input); 
public static byte[] sha1(String input, byte[] salt);
public static byte[] sha1(String input, byte[] salt, int iterations);
public static byte[] generateSalt(int numBytes);

另外对文件内容的消息摘要也提供了一套API。与前面的字符串处理不一样的是它会一边8k8k的读一边调用digest.update()而不是一次过digest()整个文件。

##Crypto加密 ###Hmac密钥签名 sha1md5只是用来摘要但因为是公开算法人人都可以对公开内容做出相同的摘要。而hmac是使用密钥的摘要等同于 Des(sha1(input)),可以达到签名的效果,保证是你自己签的。 HmacSha1Key的默认长度是160字节。

public static byte[] hmacSha1(byte[] input, byte[] key);
public static boolean isMacValid(byte[] expected, byte[] input, byte[] key);
public static byte[] generateHmacSha1Key();

###AES密钥加密 是DES协议的替代者解决了DES中的不少问题比如DES的Key长度只有64字节3DES也只有128 而AES可以是是128192和256。

和Hash中的salt值一样AES中也有一个IV(初始向量)的概念使得相同的明文会加密出不同的密文。不过要使用IV就不能使用默认的EBC分组方式加密算法要从"AES"改为"AES/CBC/PKCS5Padding"。

public static byte[] aesEncrypt(byte[] input, byte[] key)
public static byte[] aesEncrypt(byte[] input, byte[] key, byte[] iv)
public static String aesDecrypt(byte[] input, byte[] key)
public static String aesDecrypt(byte[] input, byte[] key, byte[] iv)
public static byte[] generateAesKey()
public static byte[] generateIV()

##总结 总体来说, 使用salt并1024次迭代的sha-1 Hmac 和 Aes分别是摘要签名和加密的首选协议。