Skip to content

Instantly share code, notes, and snippets.

@LGM-AdrianHum
Last active January 12, 2023 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LGM-AdrianHum/bb3533d018e3cfc8a1f773e0fc7dda17 to your computer and use it in GitHub Desktop.
Save LGM-AdrianHum/bb3533d018e3cfc8a1f773e0fc7dda17 to your computer and use it in GitHub Desktop.
Calculate the AWS S3 Checksum
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