C#获取文件MD5

什么是MD5?

​ MD5 Message-Digest Algorithm,MD5信息摘要算法。一种被广泛使用的密码散列函数,可以产生出一个128位(16字节)的散列值(hash value),用于确保信息传输完整一致。

—— 百度百科

用途是什么?

用于确保传输信息是否一致。例如文件对比,app包分发……

背景还原:

在项目中进行文件资料管理,用户上传文件时,可重复选择,对用户每次选择的文件都进行上传吗?这显然不合理,大量重复的文件文件没有意义,还会造成服务器空间资源浪费。就需要对文件进行识别,是否为重复文件。

代码实现:

方式一:

public static string getMD5ByMD5CryptoService(string path)        
{            
    if (!File.Exists(path)) return "";            
    FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);            
    MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();            
    byte[] buffer = md5Provider.ComputeHash(fs);            
    string resule = BitConverter.ToString(buffer);           
    md5Provider.Clear();            
    fs.Close();           
    return resule;        
}

方式二:

public static string getMD5ByHashAlgorithm(string path)        
{            
    if (!File.Exists(path)) return "";            
    int bufferSize = 1024 * 16;//自定义缓冲区大小16K            
    byte[] buffer = new byte[bufferSize];            
    Stream inputStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);           
    HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider();            
    int readLength = 0;//每次读取长度            
    var output = new byte[bufferSize];            
    while ((readLength = inputStream.Read(buffer, 0, buffer.Length)) > 0)            
    {               
        //计算MD5                
        hashAlgorithm.TransformBlock(buffer, 0, readLength, output, 0);            
    }            
    //完成最后计算,必须调用(由于上一部循环已经完成所有运算,所以调用此方法时后面的两个参数都为0)            		  
    hashAlgorithm.TransformFinalBlock(buffer, 0, 0);            
    string md5 = BitConverter.ToString(hashAlgorithm.Hash);                        
    hashAlgorithm.Clear();            
    inputStream.Close();            
    return md5;        
}

总结:方式一适用于小文件,一次性将文件全部读入内存,然后进行md5加密处理;方式二适用于大型文件,如果一次性读取全部文件到内存中的话,会造成系统资源占用过高,因此才去分块读取,分块加密(md5也是采取分块加密),然后在合并成完整的加密结果。

posted @ 2022-07-22 15:19  宣君  阅读(1703)  评论(0编辑  收藏  举报