Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: "Ensuring Data Integrity with Hash Codes"
description: Learn how to ensure data integrity using hash codes in .NET. A hash value is a numeric value of a fixed length that uniquely identifies data.
ms.date: 07/14/2020
ms.date: 12/28/2022
dev_langs:
- "csharp"
- "vb"
Expand All @@ -23,36 +23,26 @@ This topic describes how to generate and verify hash codes by using the classes

## Generating a Hash

The managed hash classes can hash either an array of bytes or a managed stream object. The following example uses the SHA1 hash algorithm to create a hash value for a string. The example uses the <xref:System.Text.UnicodeEncoding> class to convert the string into an array of bytes that are hashed by using the <xref:System.Security.Cryptography.SHA256> class. The hash value is then displayed to the console.
The hash classes can hash either an array of bytes or a stream object. The following example uses the SHA-256 hash algorithm to create a hash value for a string. The example uses <xref:System.Text.Encoding.UTF8?displayProperty=nameWithType> to convert the string into an array of bytes that are hashed by using the <xref:System.Security.Cryptography.SHA256> class. The hash value is then displayed to the console.

[!code-csharp[GeneratingAHash#1](../../../samples/snippets/csharp/VS_Snippets_CLR/generatingahash/cs/program.cs#1)]
[!code-vb[GeneratingAHash#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/generatingahash/vb/program.vb#1)]

This code will display the following string to the console:

`185 203 236 22 3 228 27 130 87 23 244 15 87 88 14 43 37 61 106 224 81 172 224 211 104 85 194 197 194 25 120 217`

```console
67A1790DCA55B8803AD024EE28F616A284DF5DD7B8BA5F68B4B252A5E925AF79
```

## Verifying a Hash

Data can be compared to a hash value to determine its integrity. Usually, data is hashed at a certain time and the hash value is protected in some way. At a later time, the data can be hashed again and compared to the protected value. If the hash values match, the data has not been altered. If the values do not match, the data has been corrupted. For this system to work, the protected hash must be encrypted or kept secret from all untrusted parties.

The following example compares the previous hash value of a string to a new hash value. This example loops through each byte of the hash values and makes a comparison.
The following example compares the previous hash value of a string to a new hash value.

[!code-csharp[VerifyingAHash#1](../../../samples/snippets/csharp/VS_Snippets_CLR/verifyingahash/cs/program.cs#1)]
[!code-vb[VerifyingAHash#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/verifyingahash/vb/program.vb#1)]

If the two hash values match, this code displays the following to the console:

```console
The hash codes match.
```

If they do not match, the code displays the following:

```console
The hash codes do not match.
```

## See also

- [Cryptography Model](cryptography-model.md)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,4 @@
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="System.Security.Cryptography.Xml" Version="7.0.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,14 @@
using System.Security.Cryptography;
using System.Text;

class Class1
{
static void Main(string[] args)
{
byte[] hashValue;
string messageString = "This is the original message!";

string messageString = "This is the original message!";
//Convert the string into an array of bytes.
byte[] messageBytes = Encoding.UTF8.GetBytes(messageString);

//Create a new instance of the UnicodeEncoding class to
//convert the string into an array of Unicode bytes.
UnicodeEncoding ue = new UnicodeEncoding();
//Create the hash value from the array of bytes.
byte[] hashValue = SHA256.HashData(messageBytes);

//Convert the string into an array of bytes.
byte[] messageBytes = ue.GetBytes(messageString);

//Create a new instance of the SHA256 class to create
//the hash value.
SHA256 shHash = SHA256.Create();

//Create the hash value from the array of bytes.
hashValue = shHash.ComputeHash(messageBytes);

//Display the hash value to the console.
foreach (byte b in hashValue)
{
Console.Write("{0} ", b);
}
}
}
//Display the hash value to the console.
Console.WriteLine(Convert.ToHexString(hashValue));
//</Snippet1>
Original file line number Diff line number Diff line change
@@ -1,54 +1,32 @@
//<Snippet1>
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

class Class1
{
static void Main()
{
//This hash value is produced from "This is the original message!"
//using SHA256.
byte[] sentHashValue = { 185, 203, 236, 22, 3, 228, 27, 130, 87, 23, 244, 15, 87, 88, 14, 43, 37, 61, 106, 224, 81, 172, 224, 211, 104, 85, 194, 197, 194, 25, 120, 217 };

//This is the string that corresponds to the previous hash value.
string messageString = "This is the original message!";

byte[] compareHashValue;

//Create a new instance of the UnicodeEncoding class to
//convert the string into an array of Unicode bytes.
UnicodeEncoding ue = new UnicodeEncoding();
//This hash value is produced from "This is the original message!"
//using SHA256.
byte[] sentHashValue = Convert.FromHexString("67A1790DCA55B8803AD024EE28F616A284DF5DD7B8BA5F68B4B252A5E925AF79");

//Convert the string into an array of bytes.
byte[] messageBytes = ue.GetBytes(messageString);
//This is the string that corresponds to the previous hash value.
string messageString = "This is the original message!";

//Create a new instance of the SHA256 class to create
//the hash value.
SHA256 shHash = SHA256.Create();
//Convert the string into an array of bytes.
byte[] messageBytes = Encoding.UTF8.GetBytes(messageString);

//Create the hash value from the array of bytes.
compareHashValue = shHash.ComputeHash(messageBytes);
//Create the hash value from the array of bytes.
byte[] compareHashValue = SHA256.HashData(messageBytes);

bool same = true;
//Compare the values of the two byte arrays.
bool same = sentHashValue.SequenceEqual(compareHashValue);

//Compare the values of the two byte arrays.
for (int x = 0; x < sentHashValue.Length; x++)
{
if (sentHashValue[x] != compareHashValue[x])
{
same = false;
}
}
//Display whether or not the hash values are the same.
if (same)
{
Console.WriteLine("The hash codes match.");
}
else
{
Console.WriteLine("The hash codes do not match.");
}
}
//Display whether or not the hash values are the same.
if (same)
{
Console.WriteLine("The hash codes match.");
}
else
{
Console.WriteLine("The hash codes do not match.");
}
//</Snippet1>
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,4 @@
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="System.Security.Cryptography.Xml" Version="7.0.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,16 @@ Imports System.Text

Module Program
Sub Main()
Dim hashValue() As Byte

Dim messageString As String = "This is the original message!"

'Create a new instance of the UnicodeEncoding class to
'convert the string into an array of Unicode bytes.
Dim ue As New UnicodeEncoding()

'Convert the string into an array of bytes.
Dim messageBytes As Byte() = ue.GetBytes(messageString)

'Create a new instance of the SHA256 class to create
'the hash value.
Dim shHash As SHA256 = SHA256.Create()
Dim messageBytes As Byte() = Encoding.UTF8.GetBytes(messageString)

'Create the hash value from the array of bytes.
hashValue = shHash.ComputeHash(messageBytes)
Dim hashValue As Byte() = SHA256.HashData(messageBytes)

'Display the hash value to the console.
Dim b As Byte
For Each b In hashValue
Console.Write("{0} ", b)
Next b
Console.WriteLine(Convert.ToHexString(hashValue))
End Sub
End Module
'</Snippet1>
Original file line number Diff line number Diff line change
@@ -1,41 +1,26 @@
'<Snippet1>
Imports System.Linq
Imports System.Security.Cryptography
Imports System.Text

Module Module1
Sub Main()
'This hash value is produced from "This is the original message!"
'using SHA256.
Dim sentHashValue As Byte() = {185, 203, 236, 22, 3, 228, 27, 130, 87, 23, 244, 15, 87, 88, 14, 43, 37, 61, 106, 224, 81, 172, 224, 211, 104, 85, 194, 197, 194, 25, 120, 217}
Dim sentHashValue As Byte() = Convert.FromHexString("67A1790DCA55B8803AD024EE28F616A284DF5DD7B8BA5F68B4B252A5E925AF79")

'This is the string that corresponds to the previous hash value.
Dim messageString As String = "This is the original message!"

Dim compareHashValue() As Byte

'Create a new instance of the UnicodeEncoding class to
'convert the string into an array of Unicode bytes.
Dim ue As New UnicodeEncoding()

'Convert the string into an array of bytes.
Dim messageBytes As Byte() = ue.GetBytes(messageString)

'Create a new instance of the SHA1Managed class to create
'the hash value.
Dim shHash As SHA256 = SHA256.Create()
Dim messageBytes As Byte() = Encoding.UTF8.GetBytes(messageString)

'Create the hash value from the array of bytes.
compareHashValue = shHash.ComputeHash(messageBytes)

Dim same As Boolean = True
Dim compareHashValue As Byte() = SHA256.HashData(messageBytes)

'Compare the values of the two byte arrays.
Dim x As Integer
For x = 0 To sentHashValue.Length - 1
If sentHashValue(x) <> compareHashValue(x) Then
same = False
End If
Next x
Dim same As Boolean = sentHashValue.SequenceEqual(compareHashValue)

'Display whether or not the hash values are the same.
If same Then
Console.WriteLine("The hash codes match.")
Expand Down