这部分是shiro框架的加密部分,此工具类是我自制的编码加密方法
package com.shiroweb.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
/**
* 编码解码工具类
* @author robit
*
*/
public class EncodeUtil {
private static final int SALT_SIZE = 8;
private static final String SHA1 = "SHA-1";
private static SecureRandom random = new SecureRandom();//随机数
/**
* 生成一个十六进制的字符串,作为用户加密时的salt
* 盐的原料是byte字节数组,长度为8
* @return
*/
public static String encodeHex(byte[] bytes){
return Hex.encodeHexString(bytes);
}
/**
* 获取<span style="font-family: Arial, Helvetica, sans-serif;">原料</span>盐
* @return
*/
public static byte[] baseSalt(){
byte[] bytes = new byte[SALT_SIZE];
random.nextBytes(bytes);//自动将随机数填满数组
return bytes;
}
/**
* 将16进制字符串转换为byte数组
* @param data
* @return
* @throws DecoderException
*/
public static byte[] decodeHex(String data) throws DecoderException{
return Hex.decodeHex(data.toCharArray());//对char解密
}
/**
* 将字符串进行SH1加密
* SH1加密为不可逆较慢 所以没有解密方法
* @param password 加密字符串
* @param salt 加入盐
* @param iterations 加密次数
* @return
* @throws NoSuchAlgorithmException
*/
public static byte[] encodeSH1(String password, byte[] salt, int iterations) throws NoSuchAlgorithmException{
MessageDigest digest = MessageDigest.getInstance(SHA1);
if (salt != null) {
digest.update(salt);//加入盐,更具有不可破解性
}
byte[] result = digest.digest(password.getBytes());
for(int i = 1; i < iterations; i++){
digest.reset();
result = digest.digest(result);
}
return result;
}
}