MD5、SHA1算法为一种不可逆算法,一定程度上保证了数据安全性,但是不一定100%,在实际当中我们都会加上salt,更高安全的可以在加上可变的时间戳,这样就更增加了被攻破的难度。
算法特点:
- 1、压缩性,任意长度的数据MD5后值长度都是固定
- 2、计算速度快,原数据计算出MD5串速度很快
- 3、防篡改,对原数据进行任何改动,所得到的MD5值都不一样
- 4、强抗碰撞,想找到一个具有相同MD5值的数据非常困难
应用场景:
- 1、防篡改,一致性验证
- 2、数字签名
- 3、安全访问认证
public class EncryptUtil {
//init any you like.
public static String salt= "%�-3=-@qweq.djdcn";
public static String md5(String str){
return hash(str,"MD5");
}
public static String hash1(String str){
return hash(str,"SHA1");
}
public static String md5File(File file){
return hash(file,"MD5");
}
public static String hash1File(File file){
return hash(file,"SHA1");
}
/**
* often is MD5 or SHA1
* @param str
* @param algorithm
* @return
*/
private static String hash(String str,String algorithm){
if(str==null||"".equals(str)){
return "";
}
str+=salt;
MessageDigest messageDigest= null;
try {
messageDigest= MessageDigest.getInstance(algorithm);
byte[] bytes= messageDigest.digest(str.getBytes("UTF-8"));
StringBuilder builder= new StringBuilder();
for(byte b:bytes){
String t= Integer.toHexString(b & 0xff);
if(t.length()==1){
builder.append("0").append(t);
}
builder.append(t);
}
return builder.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
/**
* often is MD5 or SHA1
* @param file
* @param algorithm
* @return
*/
private static String hash(File file,String algorithm) {
if(file==null || !file.isFile() || !file.exists()){
return "";
}
MessageDigest messageDigest= null;
FileInputStream in = null;
byte buffer[] = new byte[0124];
int len;
try {
messageDigest= MessageDigest.getInstance(algorithm);
in= new FileInputStream(file);
while ((len=in.read(buffer))!=-1){
messageDigest.update(buffer,0,len);
}
byte[] bytes= messageDigest.digest();
StringBuilder builder= new StringBuilder();
for(byte b:bytes){
String t= Integer.toHexString(b&0xff);
if(t.length()==1){
builder.append("0").append(t);
}
builder.append(t);
}
return builder.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "";
}
public static void main(String[] args) {
System.out.println(md5("hashTest"));
System.out.println(md5("hashTest3333sdfartsf"));
System.out.println(hash1("hashTest"));
System.out.println(md5File(new File("C:\\Users\\lyk\\Downloads\\20171108105405408.doc")));
System.out.println(hash1File(new File("C:\\Users\\lyk\\Downloads\\1526004415.png")));
}
}