package com.xiaopeng.vehicleConvoy.util;
|
|
|
import java.io.File;
|
import java.io.FileInputStream;
|
import java.io.IOException;
|
import java.io.UnsupportedEncodingException;
|
import java.nio.MappedByteBuffer;
|
import java.nio.channels.FileChannel;
|
|
/**
|
* 该API支持线程安全<br/>
|
*/
|
public class SHA1Util {
|
// --------------------------计算SHA1大写字符串----------------------------------------------
|
/**
|
* 计算出文件的SHA1大写字符串
|
*
|
* @param file
|
* @return
|
* @throws IOException
|
*/
|
public static String getSHA1UpperString(File file) throws IOException {
|
return HexUtil.toUpperCase(getSHA1Bytes(file));
|
}
|
|
/**
|
* 计算出SHA1后十六进制结果(大写)
|
*
|
* @param s
|
* @return
|
*/
|
public static String getSHA1UpperString(String s) {
|
try {
|
return getSHA1UpperString(s.getBytes("UTF-8"));
|
} catch (UnsupportedEncodingException e) {
|
throw new RuntimeException(e);
|
}
|
}
|
|
/**
|
* 计算出SHA1后十六进制结果(大写)
|
*
|
* @param bytes
|
* @return
|
*/
|
public static String getSHA1UpperString(byte[] bytes) {
|
return HexUtil.toUpperCase(getSHA1Bytes(bytes));
|
}
|
|
// --------------------------计算SHA1小写字符串----------------------------------------------
|
/**
|
* 计算出文件的SHA1小写字符串
|
*
|
* @param file
|
* @return
|
* @throws IOException
|
*/
|
public static String getSHA1LowerString(File file) throws IOException {
|
return HexUtil.toLowerCase(getSHA1Bytes(file));
|
}
|
|
/**
|
* 计算出SHA1后十六进制结果(小写)
|
*
|
* @param s
|
* @return
|
*/
|
public static String getSHA1LowerString(String s) {
|
try {
|
return getSHA1LowerString(s.getBytes("UTF-8"));
|
} catch (UnsupportedEncodingException e) {
|
throw new RuntimeException(e);
|
}
|
}
|
|
/**
|
* 计算出SHA1后十六进制结果(小写)
|
*
|
* @param bytes
|
* @return
|
*/
|
public static String getSHA1LowerString(byte[] bytes) {
|
return HexUtil.toLowerCase(getSHA1Bytes(bytes));
|
}
|
|
// ------------------------计算出SHA1的byte[]------------------------------------------------
|
public static byte[] getSHA1Bytes(byte[] bytes) {
|
ThreadLocalSHA1.current().update(bytes);
|
return ThreadLocalSHA1.current().digest();
|
}
|
|
public static byte[] getSHA1Bytes(File file) throws IOException {
|
FileInputStream in = null;
|
FileChannel ch = null;
|
try {
|
in = new FileInputStream(file);
|
ch = in.getChannel();
|
|
MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
|
|
ThreadLocalSHA1.current().update(byteBuffer);
|
return ThreadLocalSHA1.current().digest();
|
} finally {
|
ResourceUtil.closeGracefully(ch);
|
ResourceUtil.closeGracefully(in);
|
}
|
}
|
|
// ------------------------------------------------------------------------
|
public static boolean checkPassword(String originContent, String sha1Content) {
|
String s = getSHA1LowerString(originContent);
|
return s.equals(sha1Content);
|
}
|
|
// ------------------------------------------------------------------------
|
|
}
|