Ensuring Data Integrity with Hash Codes - .NET (2024)

A hash value is a numeric value of a fixed length that uniquely identifies data. Hash values represent large amounts of data as much smaller numeric values, so they are used with digital signatures. You can sign a hash value more efficiently than signing the larger value. Hash values are also useful for verifying the integrity of data sent through insecure channels. The hash value of received data can be compared to the hash value of data as it was sent to determine whether the data was altered.

This topic describes how to generate and verify hash codes by using the classes in the System.Security.Cryptography namespace.

Generating a Hash

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 Encoding.UTF8 to convert the string into an array of bytes that are hashed by using the SHA256 class. The hash value is then displayed to the console.

using System;using System.IO;using System.Security.Cryptography;using System.Text;string messageString = "This is the original message!";//Convert the string into an array of bytes.byte[] messageBytes = Encoding.UTF8.GetBytes(messageString);//Create the hash value from the array of bytes.byte[] hashValue = SHA256.HashData(messageBytes);//Display the hash value to the console.Console.WriteLine(Convert.ToHexString(hashValue));
Imports System.Security.CryptographyImports System.TextModule Program Sub Main() Dim messageString As String = "This is the original message!" 'Convert the string into an array of bytes. Dim messageBytes As Byte() = Encoding.UTF8.GetBytes(messageString) 'Create the hash value from the array of bytes. Dim hashValue As Byte() = SHA256.HashData(messageBytes) 'Display the hash value to the console. Console.WriteLine(Convert.ToHexString(hashValue)) End SubEnd Module

This code will display the following string to the 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.

using System;using System.Linq;using System.Security.Cryptography;using System.Text;//This hash value is produced from "This is the original message!"//using SHA256.byte[] sentHashValue = Convert.FromHexString("67A1790DCA55B8803AD024EE28F616A284DF5DD7B8BA5F68B4B252A5E925AF79");//This is the string that corresponds to the previous hash value.string messageString = "This is the original message!";//Convert the string into an array of bytes.byte[] messageBytes = Encoding.UTF8.GetBytes(messageString);//Create the hash value from the array of bytes.byte[] compareHashValue = SHA256.HashData(messageBytes);//Compare the values of the two byte arrays.bool same = sentHashValue.SequenceEqual(compareHashValue);//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.");}
Imports System.LinqImports System.Security.CryptographyImports System.TextModule Module1 Sub Main() 'This hash value is produced from "This is the original message!" 'using SHA256. 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!" 'Convert the string into an array of bytes. Dim messageBytes As Byte() = Encoding.UTF8.GetBytes(messageString) 'Create the hash value from the array of bytes. Dim compareHashValue As Byte() = SHA256.HashData(messageBytes) 'Compare the values of the two byte arrays. 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.") Else Console.WriteLine("The hash codes do not match.") End If End SubEnd Module

See also

Ensuring Data Integrity with Hash Codes - .NET (2024)

FAQs

Ensuring Data Integrity with Hash Codes - .NET? ›

Verifying a Hash

Can hashing be used to protect data integrity? ›

Hash functions play a crucial role in ensuring data integrity. They take input data, no matter its size, and produce a fixed-size string of characters, which is the hash value. If the input data changes even slightly, the hash value will change significantly.

How hash function can be used to maintain integrity of a message? ›

A hash function (like MD5 or SHA-256) is used to generate a hash value for the data you want to transfer. You then transfer both the data and its hash. After the transfer, you hash the data again, on your machine, and compare it to the original one. If they are equal, then the transfer is successful.

What is the best hash for integrity check? ›

Probably the one most commonly used is SHA-256, which the National Institute of Standards and Technology (NIST) recommends using instead of MD5 or SHA-1. The SHA-256 algorithm returns hash value of 256-bits, or 64 hexadecimal digits.

How do you validate a hash code? ›

How do I validate a hash value? It is important that the tool you use to validate a digital hash is from an independent, and preferably, open source. You will use the tool to convert the file into a hash value which you can then manually compare with the hash value from a trusted source.

How can we ensure integrity through hash functions codes? ›

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.

Why can hash functions verify data integrity? ›

For that reason, hashes are like a fingerprint for the original data. If the data changes, the fingerprint will no longer match, and it is unlikely that any other useful data will produce the same fingerprint. Therefore, you can store these small fingerprints, or hashes, to later verify your data's integrity.

Which one way hash is used to verify the integrity of data? ›

Hash functions are used for data integrity and often in combination with digital signatures. With a good hash function, even a 1-bit change in a message will produce a different hash (on average, half of the bits change). With digital signatures, a message is hashed and then the hash itself is signed.

Is hashing a reliable way to assure the integrity of a message? ›

Hashing algorithms are used to create a message digest to ensure that data integrity is maintained. A sender creates a message digest by performing the hash function on the data files to be transmitted. The receiver performs the same action on the data received and compares the two message digests.

How is a hash algorithm used in checking the integrity of a file? ›

File Integrity Checking utilizes hashing mechanisms to create hashes of files during their creation. Later, these hashes are compared with the current hashes of the files. If the hashes match, the file is intact and unaltered. This process is vital for detecting unauthorized changes or tampering.

How to ensure message integrity? ›

The validity of a transmitted message. Message integrity means that a message has not been tampered with or altered. The most common approach is to use a hash function that combines all the bytes in the message with a secret key and produces a message digest that is difficult to reverse.

How to verify data integrity? ›

Some examples include validating that values are in the right format, checking for duplicate records, making sure relationships between tables still make sense, and comparing current data to source systems.

Which algorithm can ensure data integrity? ›

An arithmetic checksum algorithm is a method of verifying data integrity by adding up the values of all the bytes in a message and comparing the result to a predetermined value. If the values match, the data is considered to be intact. If not, the data is considered to be corrupt or tampered with.

What is a hash code in C#? ›

A hash code is a numeric value that is used to insert and identify an object in a hash-based collection, such as the Dictionary<TKey,TValue> class, the Hashtable class, or a type derived from the DictionaryBase class.

Which method is used to check the integrity of data? ›

Hash functions are commonly used to verify the integrity of data during transmission or storage. By comparing the computed hash value with the original hash value, it is possible to detect any tampering or corruption. Digital signatures provide a robust method for ensuring data integrity and authentication.

How to use hash code? ›

Use of hashCode in Hashing

The hashcode value received is referred to as a bucket number. Keys with the same hash code are present in the same bucket. In the same bucket, multiple (key, value) pairs may be stored in the form of a linked list. However, keys with different hash codes reside in different buckets.

What does hashing protect against? ›

Hashing is a one-way mathematical function that turns data into a string of nondescript text that cannot be reversed or decoded. In the context of cybersecurity, hashing is a way to keep sensitive information and data — including passwords, messages, and documents — secure.

Is hashing used to retain integrity in a software? ›

Hashing is a technique using a defined algorithm to generates a value based on the contents of information that can be used to indicate if the information is subsequently changed. This can be used to protect messages in transit between a sender and recipient or data at rest in a storage device.

Is hash function used for integrity True or false? ›

Explanation: The statement is true. The problem of designing a secure hash function reduces to that of designing a collision resistant compression function.

Top Articles
Latest Posts
Article information

Author: Eusebia Nader

Last Updated:

Views: 6554

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.