Md5加密原理

3,088 阅读2分钟

前言

项目中无论是密码的存储或者说判断文件是否是同一文件,都会用到md5算法,下面来总结一下md5加密算法。

什么是MD5加密算法?

Md5英文全称‘Message-Digest Algorithm 5’翻译过来是‘消息摘要算法5’有md2,md3,md4演变过来的,是一种单项加密算法,是不可逆的一种加密方式。

Md5加密有特点?

1.压缩性: 任意长度的数据,算出的md5值长度都是固定的

2.容易计算:从元数据计算出md5值很容易。

3.抗修改性:对原数据进行任何改动,哪怕只修改一个字节,所得到的md5值都有 很大的区别。

4.抢抗碰撞:已知原数据和其md5值,想找到一个巨头相同md5值的数据(伪造数据) 是非常困难的。

MD5应用场景: 1.一致性验证 2.数字签名 3.安全访问认证

MD5加密算法实现: 1.计算字符串md5值

public static String md5(String string) {
    if (TextUtils.isEmpty(string)) {
        return "";
    }
    MessageDigest md5 = null;
    try {
        md5 = MessageDigest.getInstance("MD5");
        byte[] bytes = md5.digest(string.getBytes());
        String result = "";
        for (byte b : bytes) {
            String temp = Integer.toHexString(b & 0xff);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            result += temp;
        }
        return result;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}

2.计算文件的md5值 public static String md5(File file) { if (file == null || !file.isFile() || !file.exists()) { return ""; } FileInputStream in = null; String result = ""; byte buffer[] = new byte[8192]; int len; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); in = new FileInputStream(file); while ((len = in.read(buffer)) != -1) { md5.update(buffer, 0, len); } byte[] bytes = md5.digest();

        	for (byte b : bytes) {
            	String temp = Integer.toHexString(b & 0xff);
            	if (temp.length() == 1) {
                	temp = "0" + temp;
            	}
            	result += temp;
        	}
    	} catch (Exception e) {
        	e.printStackTrace();
   	 	}finally {
        	if(null!=in){
            	try {
                	in.close();
            	} catch (IOException e) {
                	e.printStackTrace();
            	}
       	 }
    	}
    	return result;
	}

MD5加密安全性讨论 虽然说md5加密本身是不可逆的,但并不是不可破译的,网上有管md5 解密的资料数不胜数,破解及价值采用穷举法,就是我们平时说的跑字典,所以如何才能加大md5破解的难度呢?

1.对字符串多次md5加密

public static String md5(String string, int times) {
    if (TextUtils.isEmpty(string)) {
        return "";
    }
    String md5 = md5(string);
    for (int i = 0; i < times - 1; i++) {
        md5 = md5(md5);
    }
    return md5(md5);
}

2.md5加盐 加盐的方式也是多种多样 1.string+key 然后进行md5加密 2.用string铭文的hashcode作为盐,然后进行md5加密 3.随机生成遗传字符串作为盐,然后进行md5加密

public static String md5(String string, String slat) {
    if (TextUtils.isEmpty(string)) {
        return "";
    }
    MessageDigest md5 = null;
    try {
        md5 = MessageDigest.getInstance("MD5");
        byte[] bytes = md5.digest((string + slat).getBytes());
        String result = "";
        for (byte b : bytes) {
            String temp = Integer.toHexString(b & 0xff);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            result += temp;
        }
        return result;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}