Created
September 21, 2010 21:28
-
-
Save mausch/590598 to your computer and use it in GitHub Desktop.
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
#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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wonder if there's a simpler way to implement this.