md5 sha-1 des aes 加密

/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package org.springside.modules.security.utils;


import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;


import org.apache.commons.lang3.Validate;
import org.springside.modules.utils.Exceptions;


/**
 * 支持SHA-1/MD5消息摘要的工具类.
 * 
 * 返回ByteSource,可进一步被编码为Hex, Base64或UrlSafeBase64
 * 
 * @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);
}


public static byte[] sha1(byte[] input, byte[] salt) {
return digest(input, SHA1, salt, 1);
}


public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
return digest(input, 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 byte数组的大小
*/
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);
}
}


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值