当前位置: 七九推 > IT编程>开发语言>JavaScript > 详解MD5算法的原理以及C#和JS的实现

详解MD5算法的原理以及C#和JS的实现

2023年03月17日 JavaScript 我要评论
一、简介md5 是哈希算法(散列算法)的一种应用。hash 算法虽然被称为算法,但实际上它更像是一种思想。hash 算法没有一个固定的公式,只要符合散列思想的算法都可以被称为是 hash 算法。算法目

一、简介

md5 是哈希算法(散列算法)的一种应用。hash 算法虽然被称为算法,但实际上它更像是一种思想。hash 算法没有一个固定的公式,只要符合散列思想的算法都可以被称为是 hash 算法。

算法目的就是,把任意长度的输入(又叫做预映射 pre-image),通过散列算法变换成固定长度的输出,该输出就是散列值。

注意,不同的输入可能会散列成相同的输出,所以不能从散列值来确定唯一的输入值。

散列函数简单的说就是:一种将任意长度的消息压缩到某一固定长度的消息摘要的函数。

hash 算法是一个广义的算法,也可以认为是一种思想,使用 hash 算法可以提高存储空间的利用率,可以提高数据的查询效率,因为很难找到其逆向规律,也可以做数字签名来保障数据传递的安全性。所以hash算法被广泛地应用在互联网应用中。

散列值不同 => 原始值不同

如果两个散列值是不相同的(根据同一函数),那么这两个散列值的原始输入也是不相同的。这个特性是散列函数具有确定性的结果。

散列值相同 ≠> 原始值相同

散列函数的输入和输出不是一一对应的,如果两个散列值相同,两个输入值很可能是相同的,但不绝对肯定二者一定相等(可能出现哈希碰撞)。

关于“撞库”(credential stuffing attack)

其在网络安全中是一个古老的概念,按中文的字面意思解读,就是“碰撞数据库”的意思。“碰撞”意味着碰运气,即不一定能成功;而“数据库”中往往存储着大量敏感数据,比如我们登录一个网站所需要的用户名、密码,再比如手机号、身份证号等个人隐私信息。“撞库”在英文中的表述为 credential stuffing(密码嗅探),也非常直白的说明了撞库的主要场景:试图获取正确的账号/密码组合,大白话就是“盗号”。

二、c# 代码实现

根据传入参数,返回分大小写的 16 位或 32 位密文,并且可自定义编码规则。

// 测试
string jiamihou16 = securitymd5.md5encrypt("teststring", 16, false); // 8828701f97fa4511
string jiamihou32 = securitymd5.md5encrypt("teststring", 32);// 5b56f40f8828701f97fa4511ddcd25fb
/// <summary>
/// md5 加密方法
/// </summary>
/// <param name="md5instr">待加密字符串</param>
/// <param name="digit">位数:16/32/64</param>
/// <param name="isupper">输出大小写:true 大写;false 小写(返回为 64 位时不区分大小写)</param>
/// <param name="encoding">字符编码规则,为空默认:utf8</param>
/// <returns></returns>
public static string md5encrypt(string md5instr, int digit, bool isupper = true, encoding encoding = null)
{
    string md5outstr = string.empty;
    if (encoding == null)
        encoding = encoding.utf8;
    switch (digit)
    {
        case 16:
            // securitymd5.md5encrypt(md5instr, 16, true); // 16位大写
            // securitymd5.md5encrypt(md5instr, 16, false); // 16位小写
            var md5provider = new md5cryptoserviceprovider();
            var hashinstr16 = md5provider.computehash(encoding.getbytes(md5instr));
            md5outstr = bitconverter.tostring(hashinstr16, 4, 8);
            md5outstr = md5outstr.replace("-", "");
            if (!isupper)
                md5outstr = md5outstr.tolower();
            return md5outstr;
        case 32:
            // securitymd5.md5encrypt(md5instr, 32, true); // 32位大写
            // securitymd5.md5encrypt(md5instr, 32, false); // 32位小写
            md5 md532 = md5.create();
            byte[] hashinstr32 = md532.computehash(encoding.getbytes(md5instr));
            string upperorlowerflag = isupper ? "x2" : "x2";
            for (int i = 0; i < hashinstr32.length; i++)
            {
                md5outstr = md5outstr + hashinstr32[i].tostring(upperorlowerflag);
            }
            return md5outstr;
        case 64:
            // securitymd5.md5encrypt(md5instr, 64); // 64位加密,加密后为24位的值,例如:9gnlvzezfmzlmj963tqueq==
            md5 md564 = md5.create();
            byte[] hashinstr64 = md564.computehash(encoding.getbytes(md5instr));
            return convert.tobase64string(hashinstr64);
        default:
            return "";
    }
}

三、js 代码实现

根据传入参数,返回分大小写的 16 位或 32 位密文。

// 测试
    md5_function("teststring",16,false)
    >'8828701f97fa4511'
    md5_function("teststring",32,true)
    >'5b56f40f8828701f97fa4511ddcd25fb'

// md5 加密(入参分别是:待加密内容、返回位数、是否为大写)
function md5_function(md5instr, digit, isupper){
    function md5_rotateleft(lvalue, ishiftbits) {
        return (lvalue << ishiftbits) | (lvalue >>> (32 - ishiftbits));
    }
    function md5_addunsigned(lx, ly) {
        var lx4, ly4, lx8, ly8, lresult;
        lx8 = (lx & 0x80000000);
        ly8 = (ly & 0x80000000);
        lx4 = (lx & 0x40000000);
        ly4 = (ly & 0x40000000);
        lresult = (lx & 0x3fffffff) + (ly & 0x3fffffff);
        if (lx4 & ly4) {
            return (lresult ^ 0x80000000 ^ lx8 ^ ly8);
        }
        if (lx4 | ly4) {
            if (lresult & 0x40000000) {
                return (lresult ^ 0xc0000000 ^ lx8 ^ ly8);
            } else {
                return (lresult ^ 0x40000000 ^ lx8 ^ ly8);
            }
        } else {
            return (lresult ^ lx8 ^ ly8);
        }
    }
    function md5_f(x, y, z) {
        return (x & y) | ((~x) & z);
    }
    function md5_g(x, y, z) {
        return (x & z) | (y & (~z));
    }
    function md5_h(x, y, z) {
        return (x ^ y ^ z);
    }
    function md5_i(x, y, z) {
        return (y ^ (x | (~z)));
    }
    function md5_ff(a, b, c, d, x, s, ac) {
        a = md5_addunsigned(a, md5_addunsigned(md5_addunsigned(md5_f(b, c, d), x), ac));
        return md5_addunsigned(md5_rotateleft(a, s), b);
    };
    function md5_gg(a, b, c, d, x, s, ac) {
        a = md5_addunsigned(a, md5_addunsigned(md5_addunsigned(md5_g(b, c, d), x), ac));
        return md5_addunsigned(md5_rotateleft(a, s), b);
    };
    function md5_hh(a, b, c, d, x, s, ac) {
        a = md5_addunsigned(a, md5_addunsigned(md5_addunsigned(md5_h(b, c, d), x), ac));
        return md5_addunsigned(md5_rotateleft(a, s), b);
    };
    function md5_ii(a, b, c, d, x, s, ac) {
        a = md5_addunsigned(a, md5_addunsigned(md5_addunsigned(md5_i(b, c, d), x), ac));
        return md5_addunsigned(md5_rotateleft(a, s), b);
    };
    function md5_converttowordarray(md5instr) {
        var lwordcount;
        var lmessagelength = md5instr.length;
        var lnumberofwords_temp1 = lmessagelength + 8;
        var lnumberofwords_temp2 = (lnumberofwords_temp1 - (lnumberofwords_temp1 % 64)) / 64;
        var lnumberofwords = (lnumberofwords_temp2 + 1) * 16;
        var lwordarray = array(lnumberofwords - 1);
        var lbyteposition = 0;
        var lbytecount = 0;
        while (lbytecount < lmessagelength) {
            lwordcount = (lbytecount - (lbytecount % 4)) / 4;
            lbyteposition = (lbytecount % 4) * 8;
            lwordarray[lwordcount] = (lwordarray[lwordcount] | (md5instr.charcodeat(lbytecount) << lbyteposition));
            lbytecount++;
        }
        lwordcount = (lbytecount - (lbytecount % 4)) / 4;
        lbyteposition = (lbytecount % 4) * 8;
        lwordarray[lwordcount] = lwordarray[lwordcount] | (0x80 << lbyteposition);
        lwordarray[lnumberofwords - 2] = lmessagelength << 3;
        lwordarray[lnumberofwords - 1] = lmessagelength >>> 29;
        return lwordarray;
    };
    function md5_wordtohex(lvalue) {
        var wordtohexvalue = "", wordtohexvalue_temp = "", lbyte, lcount;
        for (lcount = 0; lcount <= 3; lcount++) {
            lbyte = (lvalue >>> (lcount * 8)) & 255;
            wordtohexvalue_temp = "0" + lbyte.tostring(16);
            wordtohexvalue = wordtohexvalue + wordtohexvalue_temp.substr(wordtohexvalue_temp.length - 2, 2);
        }
        return wordtohexvalue;
    };
    function md5_utf8encode(md5instr) {
        md5instr = md5instr?.replace(/\r\n/g, "\n");
        var utftext = "";
        for (var n = 0; n < md5instr.length; n++) {
            var c = md5instr.charcodeat(n);
            if (c < 128) {
                utftext += string.fromcharcode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += string.fromcharcode((c >> 6) | 192);
                utftext += string.fromcharcode((c & 63) | 128);
            } else {
                utftext += string.fromcharcode((c >> 12) | 224);
                utftext += string.fromcharcode(((c >> 6) & 63) | 128);
                utftext += string.fromcharcode((c & 63) | 128);
            }
        }
        return utftext;
    };
    var x = array();
    var k, aa, bb, cc, dd, a, b, c, d;
    var s11 = 7, s12 = 12, s13 = 17, s14 = 22;
    var s21 = 5, s22 = 9, s23 = 14, s24 = 20;
    var s31 = 4, s32 = 11, s33 = 16, s34 = 23;
    var s41 = 6, s42 = 10, s43 = 15, s44 = 21;
    md5instr = md5_utf8encode(md5instr);
    x = md5_converttowordarray(md5instr);
    a = 0x67452301; b = 0xefcdab89; c = 0x98badcfe; d = 0x10325476;
    for (k = 0; k < x.length; k += 16) {
        aa = a; bb = b; cc = c; dd = d;
        a = md5_ff(a, b, c, d, x[k + 0], s11, 0xd76aa478);
        d = md5_ff(d, a, b, c, x[k + 1], s12, 0xe8c7b756);
        c = md5_ff(c, d, a, b, x[k + 2], s13, 0x242070db);
        b = md5_ff(b, c, d, a, x[k + 3], s14, 0xc1bdceee);
        a = md5_ff(a, b, c, d, x[k + 4], s11, 0xf57c0faf);
        d = md5_ff(d, a, b, c, x[k + 5], s12, 0x4787c62a);
        c = md5_ff(c, d, a, b, x[k + 6], s13, 0xa8304613);
        b = md5_ff(b, c, d, a, x[k + 7], s14, 0xfd469501);
        a = md5_ff(a, b, c, d, x[k + 8], s11, 0x698098d8);
        d = md5_ff(d, a, b, c, x[k + 9], s12, 0x8b44f7af);
        c = md5_ff(c, d, a, b, x[k + 10], s13, 0xffff5bb1);
        b = md5_ff(b, c, d, a, x[k + 11], s14, 0x895cd7be);
        a = md5_ff(a, b, c, d, x[k + 12], s11, 0x6b901122);
        d = md5_ff(d, a, b, c, x[k + 13], s12, 0xfd987193);
        c = md5_ff(c, d, a, b, x[k + 14], s13, 0xa679438e);
        b = md5_ff(b, c, d, a, x[k + 15], s14, 0x49b40821);
        a = md5_gg(a, b, c, d, x[k + 1], s21, 0xf61e2562);
        d = md5_gg(d, a, b, c, x[k + 6], s22, 0xc040b340);
        c = md5_gg(c, d, a, b, x[k + 11], s23, 0x265e5a51);
        b = md5_gg(b, c, d, a, x[k + 0], s24, 0xe9b6c7aa);
        a = md5_gg(a, b, c, d, x[k + 5], s21, 0xd62f105d);
        d = md5_gg(d, a, b, c, x[k + 10], s22, 0x2441453);
        c = md5_gg(c, d, a, b, x[k + 15], s23, 0xd8a1e681);
        b = md5_gg(b, c, d, a, x[k + 4], s24, 0xe7d3fbc8);
        a = md5_gg(a, b, c, d, x[k + 9], s21, 0x21e1cde6);
        d = md5_gg(d, a, b, c, x[k + 14], s22, 0xc33707d6);
        c = md5_gg(c, d, a, b, x[k + 3], s23, 0xf4d50d87);
        b = md5_gg(b, c, d, a, x[k + 8], s24, 0x455a14ed);
        a = md5_gg(a, b, c, d, x[k + 13], s21, 0xa9e3e905);
        d = md5_gg(d, a, b, c, x[k + 2], s22, 0xfcefa3f8);
        c = md5_gg(c, d, a, b, x[k + 7], s23, 0x676f02d9);
        b = md5_gg(b, c, d, a, x[k + 12], s24, 0x8d2a4c8a);
        a = md5_hh(a, b, c, d, x[k + 5], s31, 0xfffa3942);
        d = md5_hh(d, a, b, c, x[k + 8], s32, 0x8771f681);
        c = md5_hh(c, d, a, b, x[k + 11], s33, 0x6d9d6122);
        b = md5_hh(b, c, d, a, x[k + 14], s34, 0xfde5380c);
        a = md5_hh(a, b, c, d, x[k + 1], s31, 0xa4beea44);
        d = md5_hh(d, a, b, c, x[k + 4], s32, 0x4bdecfa9);
        c = md5_hh(c, d, a, b, x[k + 7], s33, 0xf6bb4b60);
        b = md5_hh(b, c, d, a, x[k + 10], s34, 0xbebfbc70);
        a = md5_hh(a, b, c, d, x[k + 13], s31, 0x289b7ec6);
        d = md5_hh(d, a, b, c, x[k + 0], s32, 0xeaa127fa);
        c = md5_hh(c, d, a, b, x[k + 3], s33, 0xd4ef3085);
        b = md5_hh(b, c, d, a, x[k + 6], s34, 0x4881d05);
        a = md5_hh(a, b, c, d, x[k + 9], s31, 0xd9d4d039);
        d = md5_hh(d, a, b, c, x[k + 12], s32, 0xe6db99e5);
        c = md5_hh(c, d, a, b, x[k + 15], s33, 0x1fa27cf8);
        b = md5_hh(b, c, d, a, x[k + 2], s34, 0xc4ac5665);
        a = md5_ii(a, b, c, d, x[k + 0], s41, 0xf4292244);
        d = md5_ii(d, a, b, c, x[k + 7], s42, 0x432aff97);
        c = md5_ii(c, d, a, b, x[k + 14], s43, 0xab9423a7);
        b = md5_ii(b, c, d, a, x[k + 5], s44, 0xfc93a039);
        a = md5_ii(a, b, c, d, x[k + 12], s41, 0x655b59c3);
        d = md5_ii(d, a, b, c, x[k + 3], s42, 0x8f0ccc92);
        c = md5_ii(c, d, a, b, x[k + 10], s43, 0xffeff47d);
        b = md5_ii(b, c, d, a, x[k + 1], s44, 0x85845dd1);
        a = md5_ii(a, b, c, d, x[k + 8], s41, 0x6fa87e4f);
        d = md5_ii(d, a, b, c, x[k + 15], s42, 0xfe2ce6e0);
        c = md5_ii(c, d, a, b, x[k + 6], s43, 0xa3014314);
        b = md5_ii(b, c, d, a, x[k + 13], s44, 0x4e0811a1);
        a = md5_ii(a, b, c, d, x[k + 4], s41, 0xf7537e82);
        d = md5_ii(d, a, b, c, x[k + 11], s42, 0xbd3af235);
        c = md5_ii(c, d, a, b, x[k + 2], s43, 0x2ad7d2bb);
        b = md5_ii(b, c, d, a, x[k + 9], s44, 0xeb86d391);
        a = md5_addunsigned(a, aa);
        b = md5_addunsigned(b, bb);
        c = md5_addunsigned(c, cc);
        d = md5_addunsigned(d, dd);
    }
    if(digit == 16){
        if(isupper)
            return (md5_wordtohex(b) + md5_wordtohex(c)).touppercase();
        else
            return (md5_wordtohex(b) + md5_wordtohex(c)).tolowercase();
    }
    else if (digit == 32){
        if(isupper)
            return (md5_wordtohex(a) + md5_wordtohex(b) + md5_wordtohex(c) + md5_wordtohex(d)).touppercase();
        else
            return (md5_wordtohex(a) + md5_wordtohex(b) + md5_wordtohex(c) + md5_wordtohex(d)).tolowercase();
    }
    return "";
}

以上就是详解md5算法的原理以及c#和js的实现的详细内容,更多关于md5算法的资料请关注七九推其它相关文章!

(0)
打赏 微信扫一扫 微信扫一扫

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2023  七九推 保留所有权利. 粤ICP备17035492号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com