Hex加密解密方法,SH1加密方法

这部分是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;
	}
	
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值