HMACSHA256 Constructor (Byte[])

Initializes a new instance of the HMACSHA256 class with the specified key data.

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

public HMACSHA256(
	byte[] key


Type: System.Byte[]
The secret key for HMACSHA256 encryption. The key can be any length, but if it is more than 64 bytes long it will be hashed (using SHA-1) to derive a 64-byte key. Therefore, the recommended size of the secret key is 64 bytes.


The key parameter is null.

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.

The following example shows how to use the HMACSHA256 constructor to encrypt an isolated storage file. This code example is part of a larger example provided for the HMACSHA256 class.

// 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];
    // Read from the wrapping CryptoStream.
    bytesRead = inStream.Read(buffer, 0, 1024);
    outStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);


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.

Community Additions