Click to Rate and Give Feedback
MSDN
MSDN Library
Web Development
Silverlight 3
HMACSHA256 Class
Collapse All/Expand All Collapse All
.NET Framework Class Library for Silverlight
HMACSHA256 Class

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

Namespace:  System.Security.Cryptography
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic (Declaration)
<ComVisibleAttribute(True)> _
Public Class HMACSHA256 _
    Inherits HMAC
Visual Basic (Usage)
Dim instance As HMACSHA256
C#
[ComVisibleAttribute(true)]
public class HMACSHA256 : HMAC

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 encode and decode a file by using the HMACSHA256 class. To build and run this example, create a Silverlight-based application in Visual Studio named HMACSHA256Example and replace the MainPage.xaml file and the MainPage.xaml.cs (or MainPage.xaml.vb) file with the following code.

NoteNote:

If the XAML code is not displayed, click the Language Filter arrow at the top of this page, and select the XAML check box.

Visual Basic
Imports System
Imports System.Windows.Controls
Imports System.Windows.Input
Imports System.IO
Imports System.IO.IsolatedStorage
Imports System.Security.Cryptography
Imports System.Security.Permissions
Imports System.Text
Class MainPage
    Inherits UserControl
    Private Shared encryptedFiles As String = ""
    Private Shared store As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
    Private Const PasswordSalt As String = "PasswordSalt"
    Private Shared sourceFilePath As String = ""
    Private Shared signedFilePath As String = ""

    Public Sub New()
        InitializeComponent()
        AddHandler Me.inputBox.KeyDown, AddressOf inputBox_KeyDown
        AddHandler Me.passwordBox.KeyDown, AddressOf passwordBox_KeyDown
        AddHandler Me.decodePassWordBox.KeyDown, AddressOf decodePassWordBox_KeyDown
        AddHandler Me.deleteBox.KeyDown, AddressOf deleteBox_KeyDown
        AddHandler Me.decodeBox.KeyDown, AddressOf decodeBox_KeyDown

        store.CreateDirectory("MyFiles")

        ' Create subdirectory under MyFiles.
        encryptedFiles = System.IO.Path.Combine("MyFiles", "EncryptedFiles")
        store.CreateDirectory(encryptedFiles)
        ListFiles()
        inputBox.Focus()

    End Sub 'New   
    Private Sub inputBox_KeyDown(ByVal sender As Object, ByVal e As EventArgs)
        If CType(e, System.Windows.Input.KeyEventArgs).Key = Key.Enter Then
            CreateFile()
            Me.passwordBox.Focus()
        End If

    End Sub 'inputBox_KeyDown   
    Private Sub decodeBox_KeyDown(ByVal sender As Object, ByVal e As EventArgs)
        If CType(e, System.Windows.Input.KeyEventArgs).Key = Key.Enter Then
            Dim store As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
            signedFilePath = System.IO.Path.Combine(encryptedFiles, "signedFile.txt")
            Me.decodePassWordBox.Focus()
        End If

    End Sub 'decodeBox_KeyDown    
    Private Sub ListFiles()
        Dim searchpath As String = System.IO.Path.Combine(encryptedFiles, "*.*")
        Dim filesInSubDirs As String() = store.GetFileNames(searchpath)
        Dim sb As New StringBuilder()
        ' List files in MyFiles\EncryptedFiles.
        sb.AppendLine("Files in MyFiles\EncryptedFiles:")
        Dim fileName As String
        For Each fileName In filesInSubDirs
            sb.AppendLine(" - " + fileName)
        Next fileName
        sb.AppendLine()
        outputBlock.Text = sb.ToString()

    End Sub 'ListFiles   
    Private Sub deleteBox_KeyDown(ByVal sender As Object, ByVal e As EventArgs)

        If CType(e, System.Windows.Input.KeyEventArgs).Key = Key.Enter Then
            store.DeleteFile(encryptedFiles + "\" + deleteBox.Text)
            ListFiles()
            Me.passwordBox.Focus()
        End If

    End Sub 'deleteBox_KeyDown   
    Private Sub passwordBox_KeyDown(ByVal sender As Object, ByVal e As EventArgs)
        If CType(e, System.Windows.Input.KeyEventArgs).Key = Key.Enter Then
            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) {}
                Dim deriveBytes As New Rfc2898DeriveBytes(passwordBox.Password, Encoding.UTF8.GetBytes(PasswordSalt))
                secretkey = deriveBytes.GetBytes(64)

                ' Use the secret key to encode the message file.
                EncodeFile(secretkey, sourceFilePath, signedFilePath)

            Catch ex As Exception
                outputBlock.Text = ex.Message
            End Try
            Me.decodePassWordBox.Focus()
        End If

    End Sub 'passwordBox_KeyDown    
    Private Sub decodePassWordBox_KeyDown(ByVal sender As Object, ByVal e As EventArgs)
        If CType(e, System.Windows.Input.KeyEventArgs).Key = Key.Enter Then
            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) {}
                Dim deriveBytes As New Rfc2898DeriveBytes(passwordBox.Password, Encoding.UTF8.GetBytes(PasswordSalt))
                secretkey = deriveBytes.GetBytes(64)

                ' Take the encoded file and decode
                DecodeFile(secretkey, signedFilePath)
            Catch ex As Exception
                outputBlock.Text = ex.Message
            End Try
            Me.deleteBox.Focus()
        End If

    End Sub 'decodePassWordBox_KeyDown    
    ' Computes a keyed hash for a source file, creates a target file with the keyed hash
    ' prepended to the contents of the source file
    Public Sub EncodeFile(ByVal key() As Byte, ByVal sourceFile As String, ByVal destFile As String)
        Dim isoStore As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
        Try
            Dim outStream As IsolatedStorageFileStream = isoStore.OpenFile(signedFilePath, FileMode.Open)
            Try
                Try
                    ' Initialize the keyed hash object.
                    Dim myhmacsha256 As New HMACSHA256(key)
                    Dim inStream As IsolatedStorageFileStream = isoStore.OpenFile(sourceFilePath, FileMode.Open)
                    inStream.Position = 0
                    ' Compute the hash of the input file.
                    Dim hashValue As Byte() = myhmacsha256.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
                    myhmacsha256.Clear()
                    ' Close the streams
                    inStream.Close()
                    outStream.Close()
                    decodeBox.Text = destFile.Replace(encryptedFiles + "\", "")
                    decodePassWordBox.Focus()
                    Return
                Catch e As Exception
                    outputBlock.Text = e.Message
                End Try
            Finally
                outStream.Dispose()
            End Try
        Finally
            isoStore.Dispose() 'end if-else
        End Try

    End Sub 'EncodeFile
    ' end EncodeFile
    ' Decode the encoded file and compare to original file.
    Public Function DecodeFile(ByVal key() As Byte, ByVal sourceFile As String) As Boolean
        Dim isoStore As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
        Try
            Dim inStream As IsolatedStorageFileStream = isoStore.OpenFile(signedFilePath, FileMode.Open)
            Try
                Try
                    ' Initialize the keyed hash object. 
                    Dim hmacsha256 As New HMACSHA256(key)
                    ' Create an array to hold the keyed hash value read from the file.
                    Dim storedHash(hmacsha256.HashSize / 8 - 1) As Byte
                    ' Create a FileStream for the source file
                    ' Read in the storedHash.
                    inStream.Read(storedHash, 0, storedHash.Length)
                    ' 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() = hmacsha256.ComputeHash(inStream)
                    ' compare the computed hash with the stored value
                    Dim i As Integer
                    For i = 1 To storedHash.Length - 1
                        If computedHash(i) <> storedHash(i) Then
                            outputBlock.Text = "Hash values differ! Either wrong password or file has changed."
                            Return False
                        End If
                    Next i
                    outputBlock.Text = "Hash values agree -- no tampering occurred."
                    Return True
                Catch e As Exception
                    outputBlock.Text = e.Message
                    Return False
                End Try
            Finally
                inStream.Dispose()
            End Try
        Finally
            isoStore.Dispose()
        End Try
        'end DecodeFile
    End Function 'DecodeFile   
    Public Sub CreateFile()
        Dim store As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
        sourceFilePath = System.IO.Path.Combine(encryptedFiles, "sourceFile.txt")
        signedFilePath = System.IO.Path.Combine(encryptedFiles, "signedFile.txt")
        Dim sourceStream As IsolatedStorageFileStream = store.CreateFile(sourceFilePath)
        Dim sw As New StreamWriter(sourceStream)
        sw.WriteLine(inputBox.Text)
        sw.Close()
        sourceStream.Close()

        Dim signedStream As IsolatedStorageFileStream = store.CreateFile(signedFilePath)
        signedStream.Close()
        decodeBox.Text = "sourceFile.txt"

    End Sub 'CreateFile
End Class 'Page
C#
using System;
using System.Windows.Controls;
using System.Windows.Input;
using System.IO;
using System.IO.IsolatedStorage;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;

namespace HMACSHA256Example
{
    public partial class MainPage : UserControl
    {
        // Initialized in Page ctor.
        private static string encryptedFiles = "";
        private static IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
        private const string PasswordSalt = "PasswordSalt";
        private static string sourceFilePath = "";
        private static string signedFilePath = "";
        public MainPage()
        {
            InitializeComponent();
            this.inputBox.KeyDown += new KeyEventHandler(inputBox_KeyDown);
            this.passwordBox.KeyDown += new KeyEventHandler(passwordBox_KeyDown);
            this.decodePassWordBox.KeyDown += new KeyEventHandler(decodePassWordBox_KeyDown);
            this.deleteBox.KeyDown += new KeyEventHandler(deleteBox_KeyDown);
            this.decodeBox.KeyDown += new KeyEventHandler(decodeBox_KeyDown);

            store.CreateDirectory("MyFiles");

            // Create subdirectory under MyFiles.
            encryptedFiles = System.IO.Path.Combine("MyFiles", "EncryptedFiles");
            store.CreateDirectory(encryptedFiles);
            ListFiles();
            inputBox.Focus();
        }
        private void inputBox_KeyDown(object sender, EventArgs e)
        {
            if (((System.Windows.Input.KeyEventArgs)e).Key == Key.Enter)
            {
                CreateFile();
                this.passwordBox.Focus();
            }
            if (((System.Windows.Input.KeyEventArgs)e).Key == Key.Tab)
            {
                CreateFile();
                this.inputBox.Focus();
            }
        }
        private void decodeBox_KeyDown(object sender, EventArgs e)
        {
            if (((System.Windows.Input.KeyEventArgs)e).Key == Key.Enter)
            {
                IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
                signedFilePath = System.IO.Path.Combine(encryptedFiles, "signedFile.txt");
                this.decodePassWordBox.Focus();
            }
        }
        private void ListFiles()
        {
            string searchpath = System.IO.Path.Combine(encryptedFiles, "*.*");
            string[] filesInSubDirs = store.GetFileNames(searchpath);
            StringBuilder sb = new StringBuilder();
            // List files in MyFiles\EncryptedFiles.
            sb.AppendLine(@"Files in MyFiles\EncryptedFiles:");
            foreach (string fileName in filesInSubDirs)
            {
                sb.AppendLine(" - " + fileName);
            }
            sb.AppendLine();
            outputBlock.Text = sb.ToString();
        }
        private void deleteBox_KeyDown(object sender, EventArgs e)
        {

            if (((System.Windows.Input.KeyEventArgs)e).Key == Key.Enter)
            {
                store.DeleteFile(encryptedFiles + "\\" + deleteBox.Text);
                ListFiles();
                this.passwordBox.Focus();
            }
        }
        private void passwordBox_KeyDown(object sender, EventArgs e)
        {
            if (((System.Windows.Input.KeyEventArgs)e).Key == Key.Enter)
            {
                try
                {
                    // Create a random key using a random number generator. This would be the
                    //  secret key shared by sender and receiver.
                    byte[] secretkey = new Byte[64];
                    Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(passwordBox.Password, Encoding.UTF8.GetBytes(PasswordSalt));
                    secretkey = deriveBytes.GetBytes(64);

                    // Use the secret key to encode the message file.
                    EncodeFile(secretkey, sourceFilePath, signedFilePath);

                }
                catch (Exception ex)
                {
                    outputBlock.Text = ex.Message;
                }
                this.decodePassWordBox.Focus();
            }

        }
        private void decodePassWordBox_KeyDown(object sender, EventArgs e)
        {
            if (((System.Windows.Input.KeyEventArgs)e).Key == Key.Enter)
            {
                try
                {
                    // Create a random key using a random number generator. This would be the
                    //  secret key shared by sender and receiver.
                    byte[] secretkey = new Byte[64];
                    Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(passwordBox.Password, Encoding.UTF8.GetBytes(PasswordSalt));
                    secretkey = deriveBytes.GetBytes(64);

                    // Take the encoded file and decode
                    DecodeFile(secretkey, signedFilePath);
                }
                catch (Exception ex)
                {
                    outputBlock.Text = ex.Message;
                }
                this.deleteBox.Focus();
            }
        }
        // Computes a keyed hash for a source file, creates a target file with the keyed hash
        // prepended to the contents of the source file
        public void EncodeFile(byte[] key, String sourceFile, String destFile)
        {
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            using (IsolatedStorageFileStream outStream = isoStore.OpenFile(signedFilePath, FileMode.Open))
            {
                try
                {
                    // Initialize the keyed hash object.
                    HMACSHA256 myhmacsha256 = new HMACSHA256(key);
                    IsolatedStorageFileStream inStream = isoStore.OpenFile(sourceFilePath, FileMode.Open);
                    inStream.Position = 0;
                    // Compute the hash of the input file.
                    byte[] hashValue = myhmacsha256.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.
                    int bytesRead;
                    // read 1K at a time
                    byte[] buffer = new byte[1024];
                    do
                    {
                        // Read from the wrapping CryptoStream.
                        bytesRead = inStream.Read(buffer, 0, 1024);
                        outStream.Write(buffer, 0, bytesRead);
                    } while (bytesRead > 0);
                    myhmacsha256.Clear();
                    // Close the streams
                    inStream.Close();
                    outStream.Close();
                    decodeBox.Text = destFile.Replace(encryptedFiles + "\\", "");
                    decodePassWordBox.Focus();
                    return;
                }
                catch (Exception e)
                {
                    outputBlock.Text = e.Message;
                }
            } //end if-else

        } // end EncodeFile
        // Decode the encoded file and compare to original file.
        public bool DecodeFile(byte[] key, String sourceFile)
        {
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            using (IsolatedStorageFileStream inStream = isoStore.OpenFile(signedFilePath, FileMode.Open))
            {
                try
                {
                    // Initialize the keyed hash object. 
                    HMACSHA256 hmacsha256 = new HMACSHA256(key);
                    // Create an array to hold the keyed hash value read from the file.
                    byte[] storedHash = new byte[hmacsha256.HashSize / 8];
                    // Create a FileStream for the source file
                    // Read in the storedHash.
                    inStream.Read(storedHash, 0, storedHash.Length);
                    // 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.
                    byte[] computedHash = hmacsha256.ComputeHash(inStream);
                    // compare the computed hash with the stored value
                    for (int i = 0; i < storedHash.Length; i++)
                    {
                        if (computedHash[i] != storedHash[i])
                        {
                            outputBlock.Text = "Hash values differ! Either wrong password or file has changed.";
                            return false;
                        }
                    }
                    outputBlock.Text = "Hash values agree -- no tampering occurred.";
                    return true;
                }
                catch (Exception e)
                {
                    outputBlock.Text = e.Message;
                    return false;
                }
            }
        } //end DecodeFile
        public void CreateFile()
        {
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
            sourceFilePath = System.IO.Path.Combine(encryptedFiles, "sourceFile.txt");
            signedFilePath = System.IO.Path.Combine(encryptedFiles, "signedFile.txt");
            IsolatedStorageFileStream sourceStream = store.CreateFile(sourceFilePath);
            StreamWriter sw = new StreamWriter(sourceStream);
            sw.WriteLine(inputBox.Text);
            sw.Close();
            sourceStream.Close();

            IsolatedStorageFileStream signedStream = store.CreateFile(signedFilePath);
            signedStream.Close();
            decodeBox.Text = "sourceFile.txt";
        }
    }
}
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
XAML Missing      RUBr777   |   Edit   |   Show History
Dear to Whom this Concern,

"

If the XAML code is not displayed, click the Language Filter arrow at the top of this page, and select the XAML check box.

"

...there is no xaml code...


Thank you,
Rune

Please send me the code (RuneBrattas@videotron.ca)
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker