0 out of 1 rated this helpful - Rate this topic

HMACSHA256 Class

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

Namespace:  System.Security.Cryptography
Assembly:  mscorlib (in mscorlib.dll)
[ComVisibleAttribute(true)]
public class HMACSHA256 : HMAC

The HMACSHA256 type exposes the following members.

  Name Description
Public method Supported by Silverlight for Windows Phone HMACSHA256() Initializes a new instance of the HMACSHA256 class with a randomly generated key.
Public method Supported by Silverlight for Windows Phone HMACSHA256(Byte[]) Initializes a new instance of the HMACSHA256 class with the specified key data.
Top
  Name Description
Protected property Supported by Silverlight for Windows Phone BlockSizeValue Gets or sets the block size to use in the hash value. (Inherited from HMAC.)
Public property Supported by Silverlight for Windows Phone CanReuseTransform Gets a value indicating whether the current transform can be reused. (Inherited from HashAlgorithm.)
Public property Supported by Silverlight for Windows Phone CanTransformMultipleBlocks When overridden in a derived class, gets a value indicating whether multiple blocks can be transformed. (Inherited from HashAlgorithm.)
Public property Supported by Silverlight for Windows Phone Hash Gets the value of the computed hash code. (Inherited from HashAlgorithm.)
Public property Supported by Silverlight for Windows Phone HashName Gets or sets the name of the hash algorithm to use for hashing. (Inherited from HMAC.)
Public property Supported by Silverlight for Windows Phone HashSize Gets the size, in bits, of the computed hash code. (Inherited from HashAlgorithm.)
Public property Supported by Silverlight for Windows Phone InputBlockSize When overridden in a derived class, gets the input block size. (Inherited from HashAlgorithm.)
Public property Supported by Silverlight for Windows Phone Key Gets or sets the key to use in the hash algorithm. (Inherited from HMAC.)
Public property Supported by Silverlight for Windows Phone OutputBlockSize When overridden in a derived class, gets the output block size. (Inherited from HashAlgorithm.)
Top
  Name Description
Public method Supported by Silverlight for Windows Phone Clear Releases all resources used by the HashAlgorithm class. (Inherited from HashAlgorithm.)
Public method Supported by Silverlight for Windows Phone ComputeHash(Byte[]) Computes the hash value for the specified byte array. (Inherited from HashAlgorithm.)
Public method Supported by Silverlight for Windows Phone ComputeHash(Stream) Computes the hash value for the specified Stream object. (Inherited from HashAlgorithm.)
Public method Supported by Silverlight for Windows Phone ComputeHash(Byte[], Int32, Int32) Computes the hash value for the specified region of the specified byte array. (Inherited from HashAlgorithm.)
Protected method Supported by Silverlight for Windows Phone Dispose Releases the unmanaged resources used by the HMAC class when a key change is legitimate and optionally releases the managed resources. (Inherited from HMAC.)
Public method Supported by Silverlight for Windows Phone Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Supported by Silverlight for Windows Phone Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public method Supported by Silverlight for Windows Phone GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method Supported by Silverlight for Windows Phone GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method Supported by Silverlight for Windows Phone HashCore When overridden in a derived class, routes data written to the object into the default HMAC hash algorithm for computing the hash value. (Inherited from HMAC.)
Protected method Supported by Silverlight for Windows Phone HashFinal When overridden in a derived class, finalizes the hash computation after the last data is processed by the cryptographic stream object. (Inherited from HMAC.)
Public method Supported by Silverlight for Windows Phone Initialize Initializes an instance of the default implementation of HMAC. (Inherited from HMAC.)
Protected method Supported by Silverlight for Windows Phone MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Supported by Silverlight for Windows Phone ToString Returns a string that represents the current object. (Inherited from Object.)
Public method Supported by Silverlight for Windows Phone TransformBlock Computes the hash value for the specified region of the input byte array and copies the resulting hash value to the specified region of the output byte array. (Inherited from HashAlgorithm.)
Public method Supported by Silverlight for Windows Phone TransformFinalBlock Computes the hash value for the specified region of the specified byte array. (Inherited from HashAlgorithm.)
Top
  Name Description
Protected field Supported by Silverlight for Windows Phone HashSizeValue Represents the size, in bits, of the computed hash code. (Inherited from HashAlgorithm.)
Protected field Supported by Silverlight for Windows Phone HashValue Represents the value of the computed hash code. (Inherited from HashAlgorithm.)
Protected field Supported by Silverlight for Windows Phone KeyValue The key to use in the hash algorithm. (Inherited from KeyedHashAlgorithm.)
Protected field Supported by Silverlight for Windows Phone State Represents the state of the hash computation. (Inherited from HashAlgorithm.)
Top
  Name Description
Explicit interface implemetation Private method Supported by Silverlight for Windows Phone IDisposable.Dispose Releases the unmanaged resources used by the HashAlgorithm and optionally releases the managed resources. (Inherited from HashAlgorithm.)
Top

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. The example has a very basic user interface, because its purpose is to demonstrate the HMACSHA256 class, not Silverlight controls. 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.

Note Note:

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


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";
        }
    }
}



<UserControl x:Class="HMACSHA256Example.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="1024" Height="768">
    <Grid x:Name="LayoutRoot" Background="White" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="550" />
            <ColumnDefinition Width="250" />
            <!--<ColumnDefinition Width="250" />-->
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <TextBlock Grid.Row="0"  Grid.Column="0" FontSize="14" Text="Enter data for source file, press Enter to create the file"/>
        <TextBlock Grid.Row="1" Grid.Column="0" FontSize="14" Text="Enter password and press Enter to create a signed copy" />
        <TextBlock Grid.Row="2" Grid.Column="0" FontSize="14" Text="Enter file to check" />
        <TextBlock Grid.Row="3" Grid.Column="0" FontSize="14" Text="Enter password and press Enter to check" />
        <TextBlock Grid.Row="4" Grid.Column="0" FontSize="14" Text="Enter file name to delete" />
        <TextBox x:Name="inputBox" Grid.Row="0" Grid.Column="1" TabIndex="0" FontSize="12" IsReadOnly="False"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <PasswordBox x:Name="passwordBox" Grid.Row="1" Grid.Column="1" TabIndex ="1" FontSize="12"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <TextBox x:Name="decodeBox" Grid.Row="2" Grid.Column="1" TabIndex="2" FontSize="12" IsReadOnly="False"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <PasswordBox x:Name="decodePassWordBox" Grid.Row="3" TabIndex="3" Grid.Column="1" FontSize="12" BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <TextBox x:Name="deleteBox" Grid.Row="4" Grid.Column="1" TabIndex="4" FontSize="12" IsReadOnly="False"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <TextBlock x:Name="outputBlock" Grid.Row="5" Grid.Column="0" FontSize="12" TextWrapping="Wrap">
        </TextBlock>
    </Grid>
</UserControl>



<UserControl x:Class="HMACSHA256Example.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="1024" Height="768">
    <Grid x:Name="LayoutRoot" Background="White" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="550" />
            <ColumnDefinition Width="250" />
            <!--<ColumnDefinition Width="250" />-->
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <TextBlock Grid.Row="0"  Grid.Column="0" FontSize="14" Text="Enter data for source file, press Enter to create the file"/>
        <TextBlock Grid.Row="1" Grid.Column="0" FontSize="14" Text="Enter password and press Enter to create a signed copy" />
        <TextBlock Grid.Row="2" Grid.Column="0" FontSize="14" Text="Enter file to check" />
        <TextBlock Grid.Row="3" Grid.Column="0" FontSize="14" Text="Enter password and press Enter to check" />
        <TextBlock Grid.Row="4" Grid.Column="0" FontSize="14" Text="Enter file name to delete" />
        <TextBox x:Name="inputBox" Grid.Row="0" Grid.Column="1" TabIndex="0" FontSize="12" IsReadOnly="False"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <PasswordBox x:Name="passwordBox" Grid.Row="1" Grid.Column="1" TabIndex ="1" FontSize="12"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <TextBox x:Name="decodeBox" Grid.Row="2" Grid.Column="1" TabIndex="2" FontSize="12" IsReadOnly="False"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <PasswordBox x:Name="decodePassWordBox" Grid.Row="3" TabIndex="3" Grid.Column="1" FontSize="12" BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <TextBox x:Name="deleteBox" Grid.Row="4" Grid.Column="1" TabIndex="4" FontSize="12" IsReadOnly="False"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <TextBlock x:Name="outputBlock" Grid.Row="5" Grid.Column="0" FontSize="12" TextWrapping="Wrap">
        </TextBlock>
    </Grid>
</UserControl>


Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Windows Phone OS 7.0

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

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Fix this bug

In the event decodePassWordBox_KeyDown please make this change:

Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(PasswordBox.Password, Encoding.UTF8.GetBytes(PasswordSalt));

for

Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(decodePassWordBox.Password, Encoding.UTF8.GetBytes(PasswordSalt));

Regards

César Fong

Bad sample :-(

Sorry, but this is the worst MS sample code ever.
There is no XAML code (see comment above) and there is a very strange user experience:
- using textbox with enter key instead of buttons,
- Why to enter the filename in deleteBox, if nobody can change its name?
- If you mistype in deletebox, it has an unhandled exception
- Why using the output box for everything (results, exception handler, showing list)
- not to forget the double "IsolatedStorageFile store" (one static member one local)

It does not explain, it confuses! Review is urgently advised!

XAML Missing
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)