HMACSHA256 클래스

정의

SHA256 해시 기능을 사용하여 HMAC(해시 기반 메시지 인증 코드)를 계산합니다.

public ref class HMACSHA256 : System::Security::Cryptography::HMAC
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public class HMACSHA256 : System.Security.Cryptography.HMAC
public class HMACSHA256 : System.Security.Cryptography.HMAC
[System.Runtime.InteropServices.ComVisible(true)]
public class HMACSHA256 : System.Security.Cryptography.HMAC
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
type HMACSHA256 = class
    inherit HMAC
type HMACSHA256 = class
    inherit HMAC
[<System.Runtime.InteropServices.ComVisible(true)>]
type HMACSHA256 = class
    inherit HMAC
Public Class HMACSHA256
Inherits HMAC
상속
특성

예제

다음 예제에서는 파일을 사용 하 여 로그인 하는 방법의 HMACSHA256 개체 및 해당 파일을 확인 하는 방법입니다.

using namespace System;
using namespace System::IO;
using namespace System::Security::Cryptography;

// Computes a keyed hash for a source file, creates a target file with the keyed hash
// prepended to the contents of the source file, then decodes the file and compares
// the source and the decoded files.
void EncodeFile( array<Byte>^key, String^ sourceFile, String^ destFile )
{
   
   // Initialize the keyed hash object.
   HMACSHA256^ myhmacsha256 = gcnew HMACSHA256( key );
   FileStream^ inStream = gcnew FileStream( sourceFile,FileMode::Open );
   FileStream^ outStream = gcnew FileStream( destFile,FileMode::Create );
   
   // Compute the hash of the input file.
   array<Byte>^hashValue = myhmacsha256->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
   array<Byte>^buffer = gcnew array<Byte>(1024);
   do
   {
      
      // Read from the wrapping CryptoStream.
      bytesRead = inStream->Read( buffer, 0, 1024 );
      outStream->Write( buffer, 0, bytesRead );
   }
   while ( bytesRead > 0 );

   myhmacsha256->Clear();
   
   // Close the streams
   inStream->Close();
   outStream->Close();
   return;
} // end EncodeFile



// Decode the encoded file and compare to original file.
bool DecodeFile( array<Byte>^key, String^ sourceFile )
{
   
   // Initialize the keyed hash object. 
   HMACSHA256^ hmacsha256 = gcnew HMACSHA256( key );
   
   // Create an array to hold the keyed hash value read from the file.
   array<Byte>^storedHash = gcnew array<Byte>(hmacsha256->HashSize / 8);
   
   // Create a FileStream for the source file.
   FileStream^ inStream = gcnew 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.
   array<Byte>^computedHash = hmacsha256->ComputeHash( inStream );
   
   // compare the computed hash with the stored value
   bool err = false;
   for ( int i = 0; i < storedHash->Length; i++ )
   {
      if ( computedHash[ i ] != storedHash[ i ] )
      {
         err = true;
      }
   }
   if (err)
        {
            Console::WriteLine("Hash values differ! Encoded file has been tampered with!");
            return false;
        }
        else
        {
            Console::WriteLine("Hash values agree -- no tampering occurred.");
            return true;
        }

} //end DecodeFile


int main()
{
   array<String^>^Fileargs = Environment::GetCommandLineArgs();
   String^ usageText = "Usage: HMACSHA256 inputfile.txt encodedfile.hsh\nYou must specify the two file names. Only the first file must exist.\n";
   
   //If no file names are specified, write usage text.
   if ( Fileargs->Length < 3 )
   {
      Console::WriteLine( usageText );
   }
   else
   {
      try
      {
         
         // Create a random key using a random number generator. This would be the
         //  secret key shared by sender and receiver.
         array<Byte>^secretkey = gcnew array<Byte>(64);
         
         //RNGCryptoServiceProvider is an implementation of a random number generator.
         RNGCryptoServiceProvider^ rng = gcnew RNGCryptoServiceProvider;
         
         // The array is now filled with cryptographically strong random bytes.
         rng->GetBytes( secretkey );
         
         // Use the secret key to encode the message file.
         EncodeFile( secretkey, Fileargs[ 1 ], Fileargs[ 2 ] );
         
         // Take the encoded file and decode
         DecodeFile( secretkey, Fileargs[ 2 ] );
      }
      catch ( IOException^ e ) 
      {
         Console::WriteLine( "Error: File not found", e );
      }

   }
} //end main
using System;
using System.IO;
using System.Security.Cryptography;

public class HMACSHA256example
{

    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[64];
            //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 (HMACSHA256 hmac = new HMACSHA256(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 (HMACSHA256 hmac = new HMACSHA256(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 HMACSHA256example

    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](63) {}
            '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 HMACSHA256(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 HMACSHA256(key)
            ' Create an array to hold the keyed hash value read from the file.
            Dim storedHash(hmac.HashSize / 8 - 1) 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

설명

HMACSHA256 는 SHA-256 해시 함수에서 생성되고 해시 기반 HMAC(메시지 인증 코드)로 사용되는 키 지정 해시 알고리즘의 형식입니다. HMAC 프로세스 메시지 데이터를 사용 하 여 비밀 키를 혼합, 해시 함수를 사용 하 여 그 결과, 비밀 키를 사용 하 여 해당 해시 값을 다시, 혼합 및 해시 함수를 한 번 적용 합니다. 출력 해시의 길이는 256비트입니다.

발신자와 수신자 공유 비밀 키를 안전 하지 않은 채널을 통해 보낸 메시지가 훼손 되었는지 여부를 확인 하는 HMAC는 사용할 수 있습니다. 보낸 사람에 게 원본 데이터에 대 한 해시 값을 계산 하 고 원래 데이터와 해시 값을 단일 메시지로 보냅니다. 수신자는 받은 메시지에 대해 해시 값을 다시 계산 하 고 계산 된 HMAC 전송된 HMAC 일치 하는지 확인 합니다.

데이터 또는 해시 값을 변경한 비밀 키의 지식이 없어도 메시지를 변경 하 고 올바른 해시 값을 다시 만들기 때문에 불일치를 발생 합니다. 따라서 원래과 계산 된 해시 값이 일치 하는 경우에 메시지 인증 됩니다.

HMACSHA256 는 모든 크기의 키를 허용하고 256비트 길이의 해시 시퀀스를 생성합니다.

생성자

HMACSHA256()

임의로 만들어진 키를 사용하여 HMACSHA256 클래스의 새 인스턴스를 초기화합니다.

HMACSHA256(Byte[])

지정된 키 데이터를 사용하여 HMACSHA256 클래스의 새 인스턴스를 초기화합니다.

필드

HashSizeInBits

HMAC SHA256 알고리즘에서 생성된 해시 크기(비트)입니다.

HashSizeInBytes

HMAC SHA256 알고리즘에서 생성된 해시 크기(바이트)입니다.

HashSizeValue

계산된 해시 코드의 크기(비트)를 나타냅니다.

(다음에서 상속됨 HashAlgorithm)
HashValue

계산된 해시 코드의 값을 나타냅니다.

(다음에서 상속됨 HashAlgorithm)
KeyValue

해시 알고리즘에 사용할 키입니다.

(다음에서 상속됨 KeyedHashAlgorithm)
State

해시 계산의 상태를 나타냅니다.

(다음에서 상속됨 HashAlgorithm)

속성

BlockSizeValue

해시 값에 사용할 블록 크기를 가져오거나 설정합니다.

(다음에서 상속됨 HMAC)
CanReuseTransform

현재 변형을 다시 사용할 수 있는지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 HashAlgorithm)
CanTransformMultipleBlocks

파생 클래스에서 재정의된 경우 여러 개의 블록을 변형할 수 있는지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 HashAlgorithm)
Hash

계산된 해시 코드의 값을 가져옵니다.

(다음에서 상속됨 HashAlgorithm)
HashName

해시에 사용할 해시 알고리즘의 이름을 가져오거나 설정합니다.

(다음에서 상속됨 HMAC)
HashSize

계산된 HMAC의 크기를 비트 단위로 가져옵니다.

HashSize

계산된 해시 코드의 크기(비트 단위)를 가져옵니다.

(다음에서 상속됨 HashAlgorithm)
InputBlockSize

파생 클래스에 재정의된 경우 입력 블록 크기를 가져옵니다.

(다음에서 상속됨 HashAlgorithm)
Key

HMAC 계산에 사용할 키를 가져오거나 설정합니다.

Key

HMAC 계산에 사용할 키를 가져오거나 설정합니다.

(다음에서 상속됨 HMAC)
OutputBlockSize

파생 클래스에 재정의된 경우 출력 블록 크기를 가져옵니다.

(다음에서 상속됨 HashAlgorithm)

메서드

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)

HMACSHA256에서 사용하는 관리되지 않는 리소스를 해제하고, 관리되는 리소스를 선택적으로 해제할 수 있습니다.

Dispose(Boolean)

키 변경이 허용된 경우 HMAC 클래스에서 사용하는 관리되지 않는 리소스를 해제하고, 필요에 따라 관리되는 리소스를 해제할 수도 있습니다.

(다음에서 상속됨 HMAC)
Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
HashCore(Byte[], Int32, Int32)

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

HashCore(Byte[], Int32, Int32)

파생 클래스에 재정의된 경우 개체에 쓰인 데이터의 경로를 HMAC 값을 계산할 HMAC 알고리즘에 지정합니다.

(다음에서 상속됨 HMAC)
HashCore(ReadOnlySpan<Byte>)

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

HashCore(ReadOnlySpan<Byte>)

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

(다음에서 상속됨 HMAC)
HashData(Byte[], Byte[])

SHA256 알고리즘을 사용하여 데이터의 HMAC를 계산합니다.

HashData(Byte[], Stream)

SHA256 알고리즘을 사용하여 스트림의 HMAC를 계산합니다.

HashData(ReadOnlySpan<Byte>, ReadOnlySpan<Byte>)

SHA256 알고리즘을 사용하여 데이터의 HMAC를 계산합니다.

HashData(ReadOnlySpan<Byte>, ReadOnlySpan<Byte>, Span<Byte>)

SHA256 알고리즘을 사용하여 데이터의 HMAC를 계산합니다.

HashData(ReadOnlySpan<Byte>, Stream)

SHA256 알고리즘을 사용하여 스트림의 HMAC를 계산합니다.

HashData(ReadOnlySpan<Byte>, Stream, Span<Byte>)

SHA256 알고리즘을 사용하여 스트림의 HMAC를 계산합니다.

HashDataAsync(Byte[], Stream, CancellationToken)

SHA256 알고리즘을 사용하여 스트림의 HMAC를 비동기적으로 계산합니다.

HashDataAsync(ReadOnlyMemory<Byte>, Stream, CancellationToken)

SHA256 알고리즘을 사용하여 스트림의 HMAC를 비동기적으로 계산합니다.

HashDataAsync(ReadOnlyMemory<Byte>, Stream, Memory<Byte>, CancellationToken)

SHA256 알고리즘을 사용하여 스트림의 HMAC를 비동기적으로 계산합니다.

HashFinal()

알고리즘에서 마지막 데이터를 처리한 후 HMAC 계산을 종료합니다.

HashFinal()

파생 클래스에서 재정의되면 알고리즘에서 마지막 데이터를 처리한 후 HMAC 계산을 종료합니다.

(다음에서 상속됨 HMAC)
Initialize()

해시 알고리즘을 초기 상태로 다시 설정합니다.

Initialize()

HMAC의 기본 구현 인스턴스를 초기화합니다.

(다음에서 상속됨 HMAC)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)
TransformBlock(Byte[], Int32, Int32, Byte[], Int32)

입력 바이트 배열의 지정된 영역에 대한 해시 값을 계산하여 입력 바이트 배열의 지정된 영역을 출력 바이트 배열의 지정된 영역에 복사합니다.

(다음에서 상속됨 HashAlgorithm)
TransformFinalBlock(Byte[], Int32, Int32)

지정된 바이트 배열의 지정된 영역에 대해 해시 값을 계산합니다.

(다음에서 상속됨 HashAlgorithm)
TryComputeHash(ReadOnlySpan<Byte>, Span<Byte>, Int32)

지정된 바이트 배열의 해시 값을 계산하려고 시도합니다.

(다음에서 상속됨 HashAlgorithm)
TryHashData(ReadOnlySpan<Byte>, ReadOnlySpan<Byte>, Span<Byte>, Int32)

SHA256 알고리즘을 사용하여 데이터의 HMAC를 계산하려고 시도합니다.

TryHashFinal(Span<Byte>, Int32)

HMAC 알고리즘에서 마지막 데이터를 처리한 후 HMAC 계산을 완료하려고 시도합니다.

TryHashFinal(Span<Byte>, Int32)

HMAC 알고리즘에서 마지막 데이터를 처리한 후 HMAC 계산을 완료하려고 시도합니다.

(다음에서 상속됨 HMAC)

명시적 인터페이스 구현

IDisposable.Dispose()

HashAlgorithm에서 사용하는 관리되지 않는 리소스를 해제하고, 관리되는 리소스를 선택적으로 해제할 수 있습니다.

(다음에서 상속됨 HashAlgorithm)

적용 대상

추가 정보