4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C# でハッシュ値を生成する

Posted at

C#でSHA1のハッシュ値を作成するには、SHA1クラスを使用します。SHA256のハッシュ値を作成するには、SHA256クラスを使用します。

SHA1, SHA256アルゴリズムでハッシュ値を生成し、出力するプログラムです。

using System.Security.Cryptography;
using System.Text;

// See https://aka.ms/new-console-template for more information

// 文字列
string str = "Hello World";


byte[] beforeByteArray = Encoding.UTF8.GetBytes(str);

// SHA1 ハッシュ値を計算する
SHA1 sha1 = SHA1.Create();
byte[] afterByteArray1 = sha1.ComputeHash(beforeByteArray);
sha1.Clear();

// バイト配列を16進数文字列に変換
StringBuilder sb1 = new StringBuilder();
foreach (byte b in afterByteArray1)
{
    sb1.Append(b.ToString("x2"));
}

// SHA256 ハッシュ値を計算する
SHA256 sha256 = SHA256.Create();

byte[] afterByteArray2 = sha256.ComputeHash(beforeByteArray);
sha256.Clear();

// バイト配列を16進数文字列に変換
StringBuilder sb2 = new StringBuilder();
foreach (byte b in afterByteArray2) {
    sb2.Append(b.ToString("x2"));
}

Console.WriteLine("SHA1");
Console.WriteLine(sb1);

Console.WriteLine("SHA256");
Console.WriteLine(sb2);
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?