MACTripleDES クラス

定義

TripleDES を使用して、入力データ CryptoStream の MAC (Message Authentication Code) を計算します。

public ref class MACTripleDES : System::Security::Cryptography::KeyedHashAlgorithm
public class MACTripleDES : System.Security.Cryptography.KeyedHashAlgorithm
[System.Runtime.InteropServices.ComVisible(true)]
public class MACTripleDES : System.Security.Cryptography.KeyedHashAlgorithm
type MACTripleDES = class
    inherit KeyedHashAlgorithm
[<System.Runtime.InteropServices.ComVisible(true)>]
type MACTripleDES = class
    inherit KeyedHashAlgorithm
Public Class MACTripleDES
Inherits KeyedHashAlgorithm
継承
属性

次の例では、 という名前 input.txtのファイルの MAC を作成します。このファイルは、実行可能ファイルの例を含むフォルダーにあります。 MAC と元のテキストは、同じフォルダー内の という名前 encrypted.hsh のファイルに書き込まれます。 その後、署名されたファイルが読み取られ、MAC はファイルのテキスト部分に対して計算され、テキストに含まれる MAC と比較されます。

using System;
using System.IO;
using System.Security.Cryptography;

public class MACTripleDESexample
{

    public static void Main(string[] Fileargs)
    {
        string dataFile;
        string signedFile;
        //If no file names are specified, create them.
        if (Fileargs.Length < 2)
        {
            dataFile = @"text.txt";
            signedFile = "signedFile.enc";

            if (!File.Exists(dataFile))
            {
                // Create a file to write to.
                using (StreamWriter sw = File.CreateText(dataFile))
                {
                    sw.WriteLine("Here is a message to sign");
                }
            }
        }
        else
        {
            dataFile = Fileargs[0];
            signedFile = Fileargs[1];
        }
        try
        {
            // Create a random key using a random number generator. This would be the
            //  secret key shared by sender and receiver.
            byte[] secretkey = new Byte[24];
            //RNGCryptoServiceProvider is an implementation of a random number generator.
            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                // The array is now filled with cryptographically strong random bytes.
                rng.GetBytes(secretkey);

                // Use the secret key to sign the message file.
                SignFile(secretkey, dataFile, signedFile);

                // Verify the signed file
                VerifyFile(secretkey, signedFile);
            }
        }
        catch (IOException e)
        {
            Console.WriteLine("Error: File not found", e);
        }
    }  //end main
    // Computes a keyed hash for a source file and creates a target file with the keyed hash
    // prepended to the contents of the source file.
    public static void SignFile(byte[] key, String sourceFile, String destFile)
    {
        // Initialize the keyed hash object.
        using (MACTripleDES hmac = new MACTripleDES(key))
        {
            using (FileStream inStream = new FileStream(sourceFile, FileMode.Open))
            {
                using (FileStream outStream = new FileStream(destFile, FileMode.Create))
                {
                    // Compute the hash of the input file.
                    byte[] hashValue = hmac.ComputeHash(inStream);
                    // Reset inStream to the beginning of the file.
                    inStream.Position = 0;
                    // Write the computed hash value to the output file.
                    outStream.Write(hashValue, 0, hashValue.Length);
                    // Copy the contents of the sourceFile to the destFile.
                    int bytesRead;
                    // read 1K at a time
                    byte[] buffer = new byte[1024];
                    do
                    {
                        // Read from the wrapping CryptoStream.
                        bytesRead = inStream.Read(buffer, 0, 1024);
                        outStream.Write(buffer, 0, bytesRead);
                    } while (bytesRead > 0);
                }
            }
        }
        return;
    } // end SignFile

    // Compares the key in the source file with a new key created for the data portion of the file. If the keys
    // compare the data has not been tampered with.
    public static bool VerifyFile(byte[] key, String sourceFile)
    {
        bool err = false;
        // Initialize the keyed hash object.
        using (MACTripleDES hmac = new MACTripleDES(key))
        {
            // Create an array to hold the keyed hash value read from the file.
            byte[] storedHash = new byte[hmac.HashSize / 8];
            // Create a FileStream for the source file.
            using (FileStream inStream = new FileStream(sourceFile, FileMode.Open))
            {
                // Read in the storedHash.
                inStream.Read(storedHash, 0, storedHash.Length);
                // Compute the hash of the remaining contents of the file.
                // The stream is properly positioned at the beginning of the content,
                // immediately after the stored hash value.
                byte[] computedHash = hmac.ComputeHash(inStream);
                // compare the computed hash with the stored value

                for (int i = 0; i < storedHash.Length; i++)
                {
                    if (computedHash[i] != storedHash[i])
                    {
                        err = true;
                    }
                }
            }
        }
        if (err)
        {
            Console.WriteLine("Hash values differ! Signed file has been tampered with!");
            return false;
        }
        else
        {
            Console.WriteLine("Hash values agree -- no tampering occurred.");
            return true;
        }
    } //end VerifyFile
} //end class
Imports System.IO
Imports System.Security.Cryptography

Public Class MACTripleDESexample

    Public Shared Sub Main(ByVal Fileargs() As String)
        Dim dataFile As String
        Dim signedFile As String
        'If no file names are specified, create them.
        If Fileargs.Length < 2 Then
            dataFile = "text.txt"
            signedFile = "signedFile.enc"

            If Not File.Exists(dataFile) Then
                ' Create a file to write to.
                Using sw As StreamWriter = File.CreateText(dataFile)
                    sw.WriteLine("Here is a message to sign")
                End Using
            End If

        Else
            dataFile = Fileargs(0)
            signedFile = Fileargs(1)
        End If
        Try
            ' Create a random key using a random number generator. This would be the
            '  secret key shared by sender and receiver.
            Dim secretkey() As Byte = New [Byte](23) {}
            'RNGCryptoServiceProvider is an implementation of a random number generator.
            Using rng As New RNGCryptoServiceProvider()
                ' The array is now filled with cryptographically strong random bytes.
                rng.GetBytes(secretkey)

                ' Use the secret key to encode the message file.
                SignFile(secretkey, dataFile, signedFile)

                ' Take the encoded file and decode
                VerifyFile(secretkey, signedFile)
            End Using
        Catch e As IOException
            Console.WriteLine("Error: File not found", e)
        End Try

    End Sub

    ' Computes a keyed hash for a source file and creates a target file with the keyed hash
    ' prepended to the contents of the source file. 
    Public Shared Sub SignFile(ByVal key() As Byte, ByVal sourceFile As String, ByVal destFile As String)
        ' Initialize the keyed hash object.
        Using myhmac As New MACTripleDES(key)
            Using inStream As New FileStream(sourceFile, FileMode.Open)
                Using outStream As New FileStream(destFile, FileMode.Create)
                    ' Compute the hash of the input file.
                    Dim hashValue As Byte() = myhmac.ComputeHash(inStream)
                    ' Reset inStream to the beginning of the file.
                    inStream.Position = 0
                    ' Write the computed hash value to the output file.
                    outStream.Write(hashValue, 0, hashValue.Length)
                    ' Copy the contents of the sourceFile to the destFile.
                    Dim bytesRead As Integer
                    ' read 1K at a time
                    Dim buffer(1023) As Byte
                    Do
                        ' Read from the wrapping CryptoStream.
                        bytesRead = inStream.Read(buffer, 0, 1024)
                        outStream.Write(buffer, 0, bytesRead)
                    Loop While bytesRead > 0
                End Using
            End Using
        End Using
        Return

    End Sub
    ' end SignFile

    ' Compares the key in the source file with a new key created for the data portion of the file. If the keys 
    ' compare the data has not been tampered with.
    Public Shared Function VerifyFile(ByVal key() As Byte, ByVal sourceFile As String) As Boolean
        Dim err As Boolean = False
        ' Initialize the keyed hash object. 
        Using hmac As New MACTripleDES(key)
            ' Create an array to hold the keyed hash value read from the file.
            Dim storedHash(hmac.HashSize / 8) As Byte
            ' Create a FileStream for the source file.
            Using inStream As New FileStream(sourceFile, FileMode.Open)
                ' Read in the storedHash.
                inStream.Read(storedHash, 0, storedHash.Length - 1)
                ' Compute the hash of the remaining contents of the file.
                ' The stream is properly positioned at the beginning of the content, 
                ' immediately after the stored hash value.
                Dim computedHash As Byte() = hmac.ComputeHash(inStream)
                ' compare the computed hash with the stored value
                Dim i As Integer
                For i = 0 To storedHash.Length - 2
                    If computedHash(i) <> storedHash(i) Then
                        err = True
                    End If
                Next i
            End Using
        End Using
        If err Then
            Console.WriteLine("Hash values differ! Signed file has been tampered with!")
            Return False
        Else
            Console.WriteLine("Hash values agree -- no tampering occurred.")
            Return True
        End If

    End Function 'VerifyFile 
End Class
'end class

注釈

MAC を使用すると、送信者と受信者が秘密キーを共有している場合に、セキュリティで保護されていないチャネル経由で送信されたメッセージが改ざんされているかどうかを確認できます。 送信者は元のデータの MAC を計算し、両方を 1 つのメッセージとして送信します。 受信側は、受信したメッセージの MAC を再計算し、計算された MAC が送信された MAC と一致することを確認します。

データまたは MAC を変更すると、メッセージを変更して正しい MAC を再現するために秘密鍵の知識が必要になるため、不一致が発生します。 したがって、コードが一致する場合、メッセージは認証されます。

MACTripleDES は、16 バイトまたは 24 バイトの長さのキーを使用し、長さが 8 バイトのハッシュ シーケンスを生成します。

コンストラクター

MACTripleDES()

MACTripleDES クラスの新しいインスタンスを初期化します。

MACTripleDES(Byte[])

キー データを指定して、MACTripleDES クラスの新しいインスタンスを初期化します。

MACTripleDES(String, Byte[])

指定したキー データと TripleDES の指定した実装を使用して、MACTripleDES クラスの新しいインスタンスを初期化します。

フィールド

HashSizeValue

計算されたハッシュ コードのサイズをビット単位で表します。

(継承元 HashAlgorithm)
HashValue

計算されたハッシュ コードの値を表します。

(継承元 HashAlgorithm)
KeyValue

ハッシュ アルゴリズムで使用するキー。

(継承元 KeyedHashAlgorithm)
State

ハッシュ計算の状態を表します。

(継承元 HashAlgorithm)

プロパティ

CanReuseTransform

現在の変換を再利用できるかどうかを示す値を取得します。

(継承元 HashAlgorithm)
CanTransformMultipleBlocks

派生クラスでオーバーライドされると、複数のブロックを変換できるかどうかを示す値を取得します。

(継承元 HashAlgorithm)
Hash

計算されたハッシュ コードの値を取得します。

(継承元 HashAlgorithm)
HashSize

計算されたハッシュ コードのサイズをビット単位で取得します。

(継承元 HashAlgorithm)
InputBlockSize

派生クラスでオーバーライドされると、入力ブロック サイズを取得します。

(継承元 HashAlgorithm)
Key

ハッシュ アルゴリズムで使用するキーを取得または設定します。

(継承元 KeyedHashAlgorithm)
OutputBlockSize

派生クラスでオーバーライドされると、出力ブロック サイズを取得します。

(継承元 HashAlgorithm)
Padding

ハッシュ アルゴリズムで使用する埋め込みモードを取得または設定します。

メソッド

Clear()

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

(継承元 HashAlgorithm)
ComputeHash(Byte[])

指定したバイト配列のハッシュ値を計算します。

(継承元 HashAlgorithm)
ComputeHash(Byte[], Int32, Int32)

指定したバイト配列の指定した領域のハッシュ値を計算します。

(継承元 HashAlgorithm)
ComputeHash(Stream)

指定された Stream オブジェクトのハッシュ値を計算します。

(継承元 HashAlgorithm)
ComputeHashAsync(Stream, CancellationToken)

指定された Stream オブジェクトのハッシュ値を非同期に計算します。

(継承元 HashAlgorithm)
Dispose()

HashAlgorithm クラスの現在のインスタンスによって使用されているすべてのリソースを解放します。

(継承元 HashAlgorithm)
Dispose(Boolean)

MACTripleDES インスタンスによって使用されているリソースを解放します。

Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
Finalize()

MACTripleDES で使用されるアンマネージ リソースを解放します。

GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
HashCore(Byte[], Int32, Int32)

MAC (Message Authentication Code) を計算するために、オブジェクトに書き込まれたデータを TripleDES 暗号化プログラムにルーティングします。

HashCore(ReadOnlySpan<Byte>)

ハッシュを計算するために、オブジェクトに書き込んだデータをハッシュ アルゴリズムにルーティングします。

(継承元 HashAlgorithm)
HashFinal()

すべてのデータがオブジェクトに書き込まれた後に、計算された MAC (Message Authentication Code) を返します。

Initialize()

MACTripleDES のインスタンスを初期化します。

MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)
TransformBlock(Byte[], Int32, Int32, Byte[], Int32)

入力バイト配列の指定した領域のハッシュ値を計算し、入力バイト配列の指定した領域を出力バイト配列の指定した領域にコピーします。

(継承元 HashAlgorithm)
TransformFinalBlock(Byte[], Int32, Int32)

指定したバイト配列の指定した領域のハッシュ値を計算します。

(継承元 HashAlgorithm)
TryComputeHash(ReadOnlySpan<Byte>, Span<Byte>, Int32)

指定したバイト配列のハッシュ値の計算を試みます。

(継承元 HashAlgorithm)
TryHashFinal(Span<Byte>, Int32)

ハッシュ アルゴリズムによって最後のデータが処理された後、ハッシュ計算の終了を試みます。

(継承元 HashAlgorithm)

明示的なインターフェイスの実装

IDisposable.Dispose()

HashAlgorithm によって使用されているアンマネージド リソースを解放し、オプションでマネージド リソースも解放します。

(継承元 HashAlgorithm)

適用対象