HMACSHA512 클래스

정의

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

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

예제

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

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 decrypts the file and compares
// the source and the decrypted files.
void EncodeFile( array<Byte>^key, String^ sourceFile, String^ destFile )
{
   
   // Initialize the keyed hash object.
   HMACSHA512^ myhmacsha512 = gcnew HMACSHA512( 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 = myhmacsha512->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 );

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



// Decrypt the encoded file and compare to original file.
bool DecodeFile( array<Byte>^key, String^ sourceFile )
{
   
   // Initialize the keyed hash object. 
   HMACSHA512^ hmacsha512 = gcnew HMACSHA512( key );
   
   // Create an array to hold the keyed hash value read from the file.
   array<Byte>^storedHash = gcnew array<Byte>(hmacsha512->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 = hmacsha512->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: HMACSHA512 inputfile.txt encryptedfile.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 HMACSHA512example
{

    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 (HMACSHA512 hmac = new HMACSHA512(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 (HMACSHA512 hmac = new HMACSHA512(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 HMACSHA5126example

    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 HMACSHA512(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 HMACSHA512(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

설명

HMACSHA512 SHA-512 해시 함수에서 생성 되 고으로 해시 기반 메시지 인증 코드 (HMAC)를 사용 하는 키 지정된 해시 알고리즘의 형식이입니다. HMAC 프로세스는 메시지 데이터를 사용 하 여 비밀 키를 혼합 하 고 결과 해시 합니다. 해시 값을 비밀 키와 마찬가지로 혼합 이며 다시 해시 됩니다. 출력 해시는 512 비트 길이입니다.

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

원본 및 계산 된 해시 값이 일치 하는 경우에 메시지 인증 됩니다. 일치 하지 않으면 데이터 또는 해시 값을 변경 되었습니다. Hmac 비밀 키의 지식이 없어도 메시지를 변경 하 고 올바른 해시 값을 다시 만들기 때문에 변조 로부터 보안을 제공 합니다.

HMACSHA512 모든 크기의 키를 받고 512 비트 길이의 해시 시퀀스를 생성 합니다.

생성자

HMACSHA512()

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

HMACSHA512(Byte[])

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

필드

HashSizeInBits

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

HashSizeInBytes

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

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)
ProduceLegacyHmacValues
사용되지 않음.

.NET Framework 2.0 서비스 팩 1 구현과 일치하지 않는 알고리즘의 HMACSHA512 .NET Framework 2.0 구현에 대한 해결 방법을 제공합니다.

메서드

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)

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

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[])

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

HashData(Byte[], Stream)

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

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

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

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

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

HashData(ReadOnlySpan<Byte>, Stream)

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

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

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

HashDataAsync(Byte[], Stream, CancellationToken)

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

HashDataAsync(ReadOnlyMemory<Byte>, Stream, CancellationToken)

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

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

SHA512 알고리즘을 사용하여 스트림의 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)

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

TryHashFinal(Span<Byte>, Int32)

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

TryHashFinal(Span<Byte>, Int32)

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

(다음에서 상속됨 HMAC)

명시적 인터페이스 구현

IDisposable.Dispose()

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

(다음에서 상속됨 HashAlgorithm)

적용 대상

추가 정보