马会东的博客

马会东的博客

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

读取文件的md5值

阿里云这么干的

public static string ComputeContentMd5 (Stream input, long partSize)
{
    using (MD5 mD = MD5.Create ()) {
        long position = input.Position;
        PartialWrapperStream inputStream = new PartialWrapperStream (input, partSize);
        byte[] inArray = mD.ComputeHash (inputStream);
        input.Seek (position, SeekOrigin.Begin);
        return Convert.ToBase64String (inArray);
    }
}

 

webuploader上传组件获取文件md5值是这么干的,详见这里:https://codesandbox.io/s/jl3eq?file=/src/App.tsx:407-1009 

import CryptoMD5 from "crypto-js/md5";
import CryptoLatin1Encoder from "crypto-js/enc-latin1";
import CryptoBase64Encoder from "crypto-js/enc-base64";

function handleUploadClick(e: React.ChangeEvent<HTMLInputElement>) { if (!e.target.files || e.target.files.length === 0) { return; } const selectedFile = e.target.files[0]; setFile(selectedFile); const reader = new FileReader(); reader.readAsBinaryString(selectedFile); reader.onloadend = (e) => { // Calculate md5 by using CryptoJS. const gotMD5 = CryptoMD5( CryptoLatin1Encoder.parse(e.target!.result as string) ); setHexMD5(gotMD5.toString()); // hex setBase64MD5(gotMD5.toString(CryptoBase64Encoder)); // base64 }; }

 

转换成c#是这么干的

        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }

 

所以将js获取到的md5转换为阿里云md5格式如下:

        /// <summary>
        /// 将webuploader上传组件获取到的文件md5值转换为阿里云md5格式
        /// </summary>
        /// <param name="jsMd5"></param>
        /// <returns></returns>
        public static string ToAliMd5Format(string jsMd5)
        {
            //把md5字符串每两个一组转换成byte[]格式
            int chunkSize = 2;
            var hashValues = Enumerable.Range(0, jsMd5.Length / chunkSize)
        .Select(i => jsMd5.Substring(i * chunkSize, chunkSize)).Select(x => { return Convert.ToByte(x, 16); }).ToArray();
            return Convert.ToBase64String(hashValues);
        }

 

posted on 2022-07-10 10:25  马会东  阅读(1149)  评论(0编辑  收藏  举报