' Collection of code snippets by Arne Vajhøj 
' (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
﻿Imports System
Imports System.Security.Cryptography
Imports System.Text

Namespace Encrypt
    Public Class TestHashing
        ' hash: Byte() -> Byte()
        Public Shared Function Hash(alg As HashAlgorithm, content As Byte()) As Byte()
            Return alg.ComputeHash(content)
        End Function
        ' Base64 encode: Byte() -> String
        Private Shared Function Encode(b As Byte()) As String
            Return Convert.ToBase64String(b)
        End Function
        ' hash: String -> Base64 String
        Public Shared Function Hash(alg As HashAlgorithm, content As String) As String
            Return Encode(Hash(alg, Encoding.UTF8.GetBytes(content)))
        End Function
        ' test
        Private Const TEXT As String = "This is some random text to be used to test encryption."
        Private Shared Sub Test(label As String, alg As HashAlgorithm)
            Console.WriteLine(label & ":")
            Dim hashval As String = Hash(alg, TEXT)
            Console.WriteLine("  " & hashval)
            Dim hashval2 As String = Hash(alg, TEXT & TEXT)
            Console.WriteLine("  " & hashval2)
        End Sub
        Private Shared Sub Test2()
            If Hash(New SHA256Managed(), TEXT) <> "oJM3t4y26uLCLtiLLNP8bhZuZi24znFEdB+QnM2d0w4=" Then
                Throw New Exception("Ooops")
            End If
        End Sub
        Public Shared Sub Main(args As String())
            ' managed implementations
            Test("SHA-2 256 bit (managed)", New SHA256Managed())
            Test("SHA-2 384 bit (managed)", New SHA384Managed())
            Test("SHA-2 512 bit (managed)", New SHA512Managed())
            ' CAPI implementations
            Test("SHA-2 256 bit (CAPI)", New SHA256CryptoServiceProvider())
            Test("SHA-2 384 bit (CAPI)", New SHA384CryptoServiceProvider())
            Test("SHA-2 512 bit (CAPI)", New SHA512CryptoServiceProvider())
            '
            Test2()
        End Sub
    End Class
End Namespace
