英語で読む

次の方法で共有


ハッシュ コードによるデータの整合性の保証

ハッシュ値は、データを一意に識別する固定長の数値です。 ハッシュ値は、大量のデータを非常に小さな数値として表現するため、デジタル署名と一緒に使用されます。 大きな値で署名するよりも、ハッシュ値を使用すれば効率的に署名できます。 ハッシュ値は、安全でないチャネルを介して送信されたデータの整合性を検証するためにも役立ちます。 受信したデータのハッシュ値を送信したデータのハッシュ値と比較すると、データが変更されたかどうかを判断できます。

このトピックでは、System.Security.Cryptography 名前空間のクラスを使用してハッシュ コードの生成と検証を実行する方法について説明します。

ハッシュの生成

ハッシュ クラスでは、バイト配列またはストリーム オブジェクトのいずれかをハッシュできます。 SHA-256 ハッシュ アルゴリズムを使用して文字列のハッシュ値を作成する例を次に示します。 この例では、Encoding.UTF8 を使用して文字列をバイト配列に変換し、SHA256 クラスを使用してバイト配列をハッシュします。 ハッシュ値はコンソールに表示されます。

C#
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));

上記のコードは、次の文字列をコンソールに表示します。

コンソール
67A1790DCA55B8803AD024EE28F616A284DF5DD7B8BA5F68B4B252A5E925AF79

ハッシュの検証

データをハッシュ値と比較すると、整合性を判断できます。 通常、データは特定のタイミングでハッシュされ、ハッシュ値はなんらかの方法で保護されます。 後でデータをもう一度ハッシュし、保護されている値と比較できます。 ハッシュ値が一致する場合、データは変更されていません。 値が一致しない場合は、データが破損しています。 このシステムを機能させるには、保護されたハッシュを暗号化するか、信頼されていないあらゆる対象に対して内密を保つ必要があります。

文字列の前のハッシュ値を新しいハッシュ値と比較する例を次に示します。

C#
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.");
}

関連項目