「C#」文字列のSHA1ハッシュ値を取得するサンプル

2022年1月14日

書式
1.GetBytes(String)
派生クラスでオーバーライドされた場合、指定した文字列に含まれるすべての文字をバイト シーケンスにエンコードします。

2.ComputeHash(Byte[])
指定したバイト配列のハッシュ値を計算します。

3.Clear()
HashAlgorithm クラスによって使用されているすべてのリソースを解放します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using System;
using System.Security.Cryptography;
using System.Text;
namespace ConsoleApplicationSample
{
class Program
{
static void Main(string[] args)
{
// 文字列変数の定義
string target = "arkgame";
// ハッシュ値を計算
SHA1CryptoServiceProvider shsp = new SHA1CryptoServiceProvider();
// すべての文字をバイト シーケンスにエンコード
byte[] beforeByteArr = Encoding.UTF8.GetBytes(target);
// 指定したバイト配列のハッシュ値を計算
byte[] afterByteArr = shsp.ComputeHash(beforeByteArr);
// HashAlgorithm クラスによって使用されているすべてのリソースを解放
shsp.Clear();
// バイト配列を16進数文字列に変換
StringBuilder sbd = new StringBuilder();
foreach (byte bt in afterByteArr)
{
sbd.Append(bt.ToString("x2"));
}
// コンソールに出力
Console.WriteLine("SHA1ハッシュ値: " + sbd.ToString());
Console.ReadKey();
}
}
}
using System; using System.Security.Cryptography; using System.Text; namespace ConsoleApplicationSample { class Program { static void Main(string[] args) { // 文字列変数の定義 string target = "arkgame"; // ハッシュ値を計算 SHA1CryptoServiceProvider shsp = new SHA1CryptoServiceProvider(); // すべての文字をバイト シーケンスにエンコード byte[] beforeByteArr = Encoding.UTF8.GetBytes(target); // 指定したバイト配列のハッシュ値を計算 byte[] afterByteArr = shsp.ComputeHash(beforeByteArr); // HashAlgorithm クラスによって使用されているすべてのリソースを解放 shsp.Clear(); // バイト配列を16進数文字列に変換 StringBuilder sbd = new StringBuilder(); foreach (byte bt in afterByteArr) { sbd.Append(bt.ToString("x2")); } // コンソールに出力 Console.WriteLine("SHA1ハッシュ値: " + sbd.ToString()); Console.ReadKey(); } } }
using System;
using System.Security.Cryptography;
using System.Text;

namespace ConsoleApplicationSample
{
    class Program
    {
        static void Main(string[] args)
        {

            // 文字列変数の定義
            string target = "arkgame";

            // ハッシュ値を計算
            SHA1CryptoServiceProvider shsp = new SHA1CryptoServiceProvider();
            // すべての文字をバイト シーケンスにエンコード
            byte[] beforeByteArr = Encoding.UTF8.GetBytes(target);
            // 指定したバイト配列のハッシュ値を計算
            byte[] afterByteArr = shsp.ComputeHash(beforeByteArr);
            // HashAlgorithm クラスによって使用されているすべてのリソースを解放
            shsp.Clear();

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

            // コンソールに出力
            Console.WriteLine("SHA1ハッシュ値: " + sbd.ToString());

            Console.ReadKey();
        }
    }
}

実行結果
SHA1ハッシュ値: f7cb9fd654b84482c166ca18c5a7e9cffba4a9d1

C#

Posted by arkgame