Last active
January 12, 2023 01:49
-
-
Save LGM-AdrianHum/bb3533d018e3cfc8a1f773e0fc7dda17 to your computer and use it in GitHub Desktop.
Calculate the AWS S3 Checksum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static async Task<string> HashOf(string filename, int chunkSizeInMb) | |
{ | |
var returnMd5 = string.Empty; | |
var chunkSize = chunkSizeInMb * 1024 * 1024; | |
await Task.Run(() => | |
{ | |
using (var crypto = new System.Security.Cryptography.MD5CryptoServiceProvider()) | |
{ | |
var hashLength = crypto.HashSize / 8; | |
using (var stream = File.OpenRead(filename)) | |
{ | |
if (chunkSize != 0 && stream.Length > chunkSize) | |
{ | |
var chunkCount = (long)Math.Ceiling(stream.Length / (double)chunkSize); | |
var hash = new byte[chunkCount * hashLength]; | |
var hashStream = new MemoryStream(hash); | |
var 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment