GetHashStr returns the hash value of a string.
These functions can use any of the hash classes from the System.Security.Cryptography namespace, e.g. MD5, SHA1, SHA256, SHA512.
//C# using System; using System.Security.Cryptography; using System.Text; namespace ExpressionSoftware.Security.Crypt { public static class Hash { public static byte[] GetHash(byte[] bs, Type hashType) { return HashAlgorithm.Create(hashType.Name).ComputeHash(bs); } public static byte[] GetHashStr(string input, Type hashType) { byte[] bs = Encoding.UTF8.GetBytes(input); return GetHash(bs, hashType); } } }
//F# v1.9.7.8 namespace ExpressionSoftware.Security.Crypt open System open System.Security.Cryptography open System.Text module Hash = let GetHash(bs:byte[], hashType:Type) = HashAlgorithm.Create(hashType.Name).ComputeHash bs let GetHashStr(input:string, hashType:Type) = Encoding.UTF8.GetBytes input |> (fun bs -> GetHash(bs, hashType))
#PowerShell function getHash($bs, $hashType) { $hashType::create().computeHash($bs) } function getHashStr($inputStr, $hashType) { getHash ([system.text.encoding]::utf8.getBytes($inputStr)) $hashType }
Examples
//C# byte[] bs = Encoding.UTF8.GetBytes("foo"); byte[] hash = Hash.GetHash(bs, typeof(SHA1)); Debug.WriteLine(Byte.BytesToString(hash, "{0} ")); 11 238 199 181 234 63 15 219 201 93 13 212 127 60 91 194 117 218 138 51 //output
//F# let hash = Hash.GetHashStr("foo", typeof<SHA1>) Byte.BytesToString(hash, "{0:x} ") |> (fun s -> printfn "%s" s) b ee c7 b5 ea 3f f db c9 5d d d4 7f 3c 5b c2 75 da 8a 33 //output
#PowerShell $hashType = [system.security.cryptography.SHA1] $hash = getHashStr 'foo' $hashType bytesToString $hash '{0:X}' BEEC7B5EA3FFDBC95DDD47F3C5BC275DA8A33 #output
No comments:
Post a Comment