This documentation is archived and is not being maintained.

HMACSHA256 Class

Updated: May 2011

Computes a Hash-based Message Authentication Code (HMAC) using the SHA256 hash function.

Namespace:  System.Security.Cryptography
Assembly:  mscorlib (in mscorlib.dll)

'Declaration
<ComVisibleAttribute(True)> _
Public Class HMACSHA256 _
	Inherits HMAC
'Usage
Dim instance As HMACSHA256

HMACSHA256 is a type of keyed hash algorithm that is constructed from the SHA-256 hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, and then applies the hash function a second time. The output hash is 256 bits in length.

An HMAC can be used to determine whether a message sent over an insecure channel has been tampered with, provided that the sender and receiver share a secret key. The sender computes the hash value for the original data and sends both the original data and hash value as a single message. The receiver recalculates the hash value on the received message and checks that the computed HMAC matches the transmitted HMAC.

Any change to the data or the hash value results in a mismatch, because knowledge of the secret key is required to change the message and reproduce the correct hash value. Therefore, if the original and computed hash values match, the message is authenticated.

HMACSHA256 accepts keys of any size, and produces a hash sequence 256 bits in length.

The following example shows how to sign a file by using the HMACSHA256 object and then how to verify the file.

Imports System
Imports System.IO
Imports System.Security.Cryptography

Public Class HMACSHA256example

    Public Shared Sub Main(ByVal Fileargs() As String)
        Dim dataFile As String 
        Dim signedFile As String 
        'If no file names are specified, create them. 
        If Fileargs.Length < 2 Then
            dataFile = "text.txt"
            signedFile = "signedFile.enc" 

            If Not File.Exists(dataFile) Then 
                ' Create a file to write to. 
                Using sw As StreamWriter = File.CreateText(dataFile)
                    sw.WriteLine("Here is a message to sign")
                End Using 
            End If 

        Else
            dataFile = Fileargs(0)
            signedFile = Fileargs(1)
        End If 
        Try 
            ' Create a random key using a random number generator. This would be the 
            '  secret key shared by sender and receiver. 
            Dim secretkey() As Byte = New [Byte](63) {}
            'RNGCryptoServiceProvider is an implementation of a random number generator. 
            Using rng As New RNGCryptoServiceProvider()
                ' The array is now filled with cryptographically strong random bytes.
                rng.GetBytes(secretkey)

                ' Use the secret key to encode the message file.
                SignFile(secretkey, dataFile, signedFile)

                ' Take the encoded file and decode
                VerifyFile(secretkey, signedFile)
            End Using 
        Catch e As IOException
            Console.WriteLine("Error: File not found", e)
        End Try 

    End Sub 'Main

    ' Computes a keyed hash for a source file and creates a target file with the keyed hash 
    ' prepended to the contents of the source file.  
    Public Shared Sub SignFile(ByVal key() As Byte, ByVal sourceFile As String, ByVal destFile As String)
        ' Initialize the keyed hash object. 
        Using myhmac As New HMACSHA256(key)
            Using inStream As New FileStream(sourceFile, FileMode.Open)
                Using outStream As New FileStream(destFile, FileMode.Create)
                    ' Compute the hash of the input file. 
                    Dim hashValue As Byte() = myhmac.ComputeHash(inStream)
                    ' Reset inStream to the beginning of the file.
                    inStream.Position = 0
                    ' Write the computed hash value to the output file.
                    outStream.Write(hashValue, 0, hashValue.Length)
                    ' Copy the contents of the sourceFile to the destFile. 
                    Dim bytesRead As Integer 
                    ' read 1K at a time 
                    Dim buffer(1023) As Byte
                    Do
                        ' Read from the wrapping CryptoStream.
                        bytesRead = inStream.Read(buffer, 0, 1024)
                        outStream.Write(buffer, 0, bytesRead)
                    Loop While bytesRead > 0
                End Using 
            End Using 
        End Using 
        Return 

    End Sub 'SignFile
    ' end SignFile 

    ' Compares the key in the source file with a new key created for the data portion of the file. If the keys  
    ' compare the data has not been tampered with. 
    Public Shared Function VerifyFile(ByVal key() As Byte, ByVal sourceFile As String) As Boolean 
        Dim err As Boolean = False 
        ' Initialize the keyed hash object.  
        Using hmac As New HMACSHA256(key)
            ' Create an array to hold the keyed hash value read from the file. 
            Dim storedHash(hmac.HashSize / 8) As Byte
            ' Create a FileStream for the source file. 
            Using inStream As New FileStream(sourceFile, FileMode.Open)
                ' Read in the storedHash.
                inStream.Read(storedHash, 0, storedHash.Length - 1)
                ' Compute the hash of the remaining contents of the file. 
                ' The stream is properly positioned at the beginning of the content,  
                ' immediately after the stored hash value. 
                Dim computedHash As Byte() = hmac.ComputeHash(inStream)
                ' compare the computed hash with the stored value 
                Dim i As Integer 
                For i = 0 To storedHash.Length - 2
                    If computedHash(i) <> storedHash(i) Then
                        err = True 
                    End If 
                Next i
            End Using 
        End Using 
        If err Then
            Console.WriteLine("Hash values differ! Signed file has been tampered with!")
            Return False 
        Else
            Console.WriteLine("Hash values agree -- no tampering occurred.")
            Return True 
        End If 

    End Function 'VerifyFile 
End Class 'HMACSHA256example 'end VerifyFile
'end class

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0

Date

History

Reason

May 2011

Updated the code example.

Information enhancement.

Show: