MACTripleDES 클래스

정의

입력 데이터 CryptoStream에 대해 TripleDES를 사용하여 MAC(메시지 인증 코드)를 계산합니다.

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
상속
특성

예제

다음 예제에서는 라는 파일에 대 한 MAC input.txt를 실행 하는 예제를 포함 하는 폴더에 있는 합니다. 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를 계산 하 고 모두 단일 메시지로 보냅니다. 수신자는 수신된 된 메시지에서 MAC을 다시 계산 하 고 계산 된 MAC에 전송 된 MAC과 일치 하는지 확인

변경 데이터 또는 불일치를 MAC 결과 메시지를 변경 하 고 올바른 MAC을 재현 하려면 비밀 키에 대 한 지식이 필요 하므로 따라서 코드가 일치 하는 경우에 메시지 인증 됩니다.

MACTripleDES long, 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(메시지 인증 코드) 계산을 위해 TripleDES암호기로 라우트합니다.

HashCore(ReadOnlySpan<Byte>)

개체에 쓴 데이터를 해시를 계산하기 위한 해시 알고리즘으로 경로 처리합니다.

(다음에서 상속됨 HashAlgorithm)
HashFinal()

모든 데이터를 개체에 쓴 후 계산된 MAC(메시지 인증 코드)를 반환합니다.

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)

적용 대상