How to get the md5sum of a file on Amazon's S3

前端 未结 11 2168

If I have existing files on Amazon\'s S3, what\'s the easiest way to get their md5sum without having to download the files?

Thanks

11条回答
  •  心在旅途
    2020-12-01 01:13

    For anyone who spend time to search around to find out that why the md5 not the same as ETag in S3.

    ETag will calculate against chuck of data and concat all md5hash to make md5 hash again and keep the number of chunk at the end.

    Here is C# version to generate hash

        string etag = HashOf("file.txt",8);
    

    source code

        private string HashOf(string filename,int chunkSizeInMb)
        {
            string returnMD5 = string.Empty;
            int chunkSize = chunkSizeInMb * 1024 * 1024;
    
            using (var crypto = new MD5CryptoServiceProvider())
            {
                int hashLength = crypto.HashSize/8;
    
                using (var stream = File.OpenRead(filename))
                {
                    if (stream.Length > chunkSize)
                    {
                        int chunkCount = (int)Math.Ceiling((double)stream.Length/(double)chunkSize);
    
                        byte[] hash = new byte[chunkCount*hashLength];
                        Stream hashStream = new MemoryStream(hash);
    
                        long nByteLeftToRead = stream.Length;
                        while (nByteLeftToRead > 0)
                        {
                            int nByteCurrentRead = (int)Math.Min(nByteLeftToRead, chunkSize);
                            byte[] buffer = new byte[nByteCurrentRead];
                            nByteLeftToRead -= stream.Read(buffer, 0, nByteCurrentRead);
    
                            byte[] tmpHash = crypto.ComputeHash(buffer);
    
                            hashStream.Write(tmpHash, 0, hashLength);
    
                        }
    
                        returnMD5 = BitConverter.ToString(crypto.ComputeHash(hash)).Replace("-", string.Empty).ToLower()+"-"+ chunkCount;
                    }
                    else {
                        returnMD5 = BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", string.Empty).ToLower();
    
                    }
                    stream.Close();
                }
            }
            return returnMD5;
        }
    

提交回复
热议问题