Skip to content

Instantly share code, notes, and snippets.

@mausch
Created September 21, 2010 21:28
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 mausch/590598 to your computer and use it in GitHub Desktop.
Save mausch/590598 to your computer and use it in GitHub Desktop.
#r "FSharp.PowerPack"
open System
open System.IO
open System.Security.Cryptography
let hashFile f =
use fs = new FileStream(f, FileMode.Open)
use hashFunction = new SHA512Managed()
hashFunction.ComputeHash fs |> Convert.ToBase64String
let hashAsync bufferSize (hashFunction: HashAlgorithm) (stream: Stream) =
let rec hashBlock currentBlock count = async {
let buffer = Array.zeroCreate<byte> bufferSize
let! readCount = stream.AsyncRead buffer
if readCount = 0 then
hashFunction.TransformFinalBlock(currentBlock, 0, count) |> ignore
else
hashFunction.TransformBlock(currentBlock, 0, count, currentBlock, 0) |> ignore
return! hashBlock buffer readCount
}
async {
let buffer = Array.zeroCreate<byte> bufferSize
let! readCount = stream.AsyncRead buffer
do! hashBlock buffer readCount
return hashFunction.Hash |> Convert.ToBase64String
}
let hashFileAsync f =
let bufferSize = 32768
async {
use! fs = File.AsyncOpenRead f
use hashFunction = new SHA512Managed()
return! hashAsync bufferSize hashFunction fs
}
@mausch
Copy link
Author

mausch commented Sep 21, 2010

I wonder if there's a simpler way to implement this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment