SHA256 클래스

정의

입력 데이터에 대한 SHA256 해시를 계산합니다.

public ref class SHA256 abstract : System::Security::Cryptography::HashAlgorithm
public abstract class SHA256 : System.Security.Cryptography.HashAlgorithm
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class SHA256 : System.Security.Cryptography.HashAlgorithm
type SHA256 = class
    inherit HashAlgorithm
[<System.Runtime.InteropServices.ComVisible(true)>]
type SHA256 = class
    inherit HashAlgorithm
Public MustInherit Class SHA256
Inherits HashAlgorithm
상속
파생
특성

예제

다음 예제에서는 디렉터리의 모든 파일에 대한 SHA-256 해시를 계산합니다.

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

// Print the byte array in a readable format.
void PrintByteArray( array<Byte>^array )
{
   int i;
   for ( i = 0; i < array->Length; i++ )
   {
      Console::Write( String::Format( "{0:X2}", array[ i ] ) );
      if ( (i % 4) == 3 )
            Console::Write( " " );

   }
   Console::WriteLine();
}

int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();
   if ( args->Length < 2 )
   {
      Console::WriteLine( "Usage: hashdir <directory>" );
      return 0;
   }

   try
   {

      // Create a DirectoryInfo object representing the specified directory.
      DirectoryInfo^ dir = gcnew DirectoryInfo( args[ 1 ] );

      // Get the FileInfo objects for every file in the directory.
      array<FileInfo^>^files = dir->GetFiles();

      // Initialize a SHA256 hash object.
      SHA256 ^ mySHA256 = SHA256Managed::Create();
      array<Byte>^hashValue;

      // Compute and print the hash values for each file in directory.
      System::Collections::IEnumerator^ myEnum = files->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         FileInfo^ fInfo = safe_cast<FileInfo^>(myEnum->Current);

         // Create a fileStream for the file.
         FileStream^ fileStream = fInfo->Open( FileMode::Open );

         // Compute the hash of the fileStream.
         hashValue = mySHA256->ComputeHash( fileStream );

         // Write the name of the file to the Console.
         Console::Write( "{0}: ", fInfo->Name );

         // Write the hash value to the Console.
         PrintByteArray( hashValue );

         // Close the file.
         fileStream->Close();
      }
      return 0;
   }
   catch ( DirectoryNotFoundException^ ) 
   {
      Console::WriteLine( "Error: The directory specified could not be found." );
   }
   catch ( IOException^ ) 
   {
      Console::WriteLine( "Error: A file in the directory could not be accessed." );
   }

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

public class HashDirectory
{
    public static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.WriteLine("No directory selected.");
            return;
        }

        string directory = args[0];
        if (Directory.Exists(directory))
        {
            // Create a DirectoryInfo object representing the specified directory.
            var dir = new DirectoryInfo(directory);
            // Get the FileInfo objects for every file in the directory.
            FileInfo[] files = dir.GetFiles();
            // Initialize a SHA256 hash object.
            using (SHA256 mySHA256 = SHA256.Create())
            {
                // Compute and print the hash values for each file in directory.
                foreach (FileInfo fInfo in files)
                {
                    using (FileStream fileStream = fInfo.Open(FileMode.Open))
                    {
                        try
                        {
                            // Create a fileStream for the file.
                            // Be sure it's positioned to the beginning of the stream.
                            fileStream.Position = 0;
                            // Compute the hash of the fileStream.
                            byte[] hashValue = mySHA256.ComputeHash(fileStream);
                            // Write the name and hash value of the file to the console.
                            Console.Write($"{fInfo.Name}: ");
                            PrintByteArray(hashValue);
                        }
                        catch (IOException e)
                        {
                            Console.WriteLine($"I/O Exception: {e.Message}");
                        }
                        catch (UnauthorizedAccessException e)
                        {
                            Console.WriteLine($"Access Exception: {e.Message}");
                        }
                    }
                }
            }
        }
        else
        {
            Console.WriteLine("The directory specified could not be found.");
        }
    }

    // Display the byte array in a readable format.
    public static void PrintByteArray(byte[] array)
    {
        for (int i = 0; i < array.Length; i++)
        {
            Console.Write($"{array[i]:X2}");
            if ((i % 4) == 3) Console.Write(" ");
        }
        Console.WriteLine();
    }
}
Imports System.IO
Imports System.Security.Cryptography

Public Module HashDirectory

    Public Sub Main(ByVal args() As String)
        If args.Length < 1 Then
            Console.WriteLine("No directory selected")
            Return
        End If

        Dim targetDirectory As String = args(0)
        If Directory.Exists(targetDirectory) Then
            ' Create a DirectoryInfo object representing the specified directory.
            Dim dir As New DirectoryInfo(targetDirectory)
            ' Get the FileInfo objects for every file in the directory.
            Dim files As FileInfo() = dir.GetFiles()
            ' Initialize a SHA256 hash object.
            Using mySHA256 As SHA256 = SHA256.Create()
                ' Compute and print the hash values for each file in directory.
                For Each fInfo  As FileInfo In files
                    Try
                        ' Create a fileStream for the file.
                        Dim fileStream = fInfo.Open(FileMode.Open)
                        ' Be sure it's positioned to the beginning of the stream.
                        fileStream.Position = 0
                        ' Compute the hash of the fileStream.
                        Dim hashValue() As Byte = mySHA256.ComputeHash(fileStream)
                        ' Write the name of the file to the Console.
                        Console.Write(fInfo.Name + ": ")
                        ' Write the hash value to the Console.
                        PrintByteArray(hashValue)
                        ' Close the file.
                        fileStream.Close()
                    Catch e As IOException
                        Console.WriteLine($"I/O Exception: {e.Message}")
                    Catch e As UnauthorizedAccessException 
                        Console.WriteLine($"Access Exception: {e.Message}")
                    End Try    
                Next 
            End Using
        Else
           Console.WriteLine("The directory specified could not be found.")
        End If
    End Sub

    ' Print the byte array in a readable format.
    Public Sub PrintByteArray(array() As Byte)
        For i As Integer = 0 To array.Length - 1
            Console.Write($"{array(i):X2}")
            If i Mod 4 = 3 Then
                Console.Write(" ")
            End If
        Next 
        Console.WriteLine()

    End Sub 
End Module

설명

많은 양의 데이터를 나타내는 고정 된 크기의 고유 값으로 해시가 됩니다. 해당 데이터도 일치 하는 경우에 두 데이터 집합의 해시 일치 해야 합니다. 데이터 결과 해시 예측할 수 없는 큰 변화를 하려면 약간 변경 합니다.

알고리즘의 SHA256 해시 크기는 256비트입니다.

이 클래스는 추상 클래스입니다.

생성자

SHA256()

SHA256의 새 인스턴스를 초기화합니다.

필드

HashSizeInBits

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

HashSizeInBytes

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

HashSizeValue

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

(다음에서 상속됨 HashAlgorithm)
HashValue

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

(다음에서 상속됨 HashAlgorithm)
State

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

(다음에서 상속됨 HashAlgorithm)

속성

CanReuseTransform

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

(다음에서 상속됨 HashAlgorithm)
CanTransformMultipleBlocks

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

(다음에서 상속됨 HashAlgorithm)
Hash

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

(다음에서 상속됨 HashAlgorithm)
HashSize

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

(다음에서 상속됨 HashAlgorithm)
InputBlockSize

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

(다음에서 상속됨 HashAlgorithm)
OutputBlockSize

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

(다음에서 상속됨 HashAlgorithm)

메서드

Clear()

HashAlgorithm 클래스에서 사용하는 모든 리소스를 해제합니다.

(다음에서 상속됨 HashAlgorithm)
ComputeHash(Byte[])

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

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

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

(다음에서 상속됨 HashAlgorithm)
ComputeHash(Stream)

지정된 Stream 개체에 대해 해시 값을 계산합니다.

(다음에서 상속됨 HashAlgorithm)
ComputeHashAsync(Stream, CancellationToken)

지정된 Stream 개체에 대해 비동기적으로 해시 값을 계산합니다.

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

SHA256의 기본 구현 인스턴스를 만듭니다.

Create(String)

SHA256의 지정된 구현 인스턴스를 만듭니다.

Dispose()

HashAlgorithm 클래스의 현재 인스턴스에서 사용하는 모든 리소스를 해제합니다.

(다음에서 상속됨 HashAlgorithm)
Dispose(Boolean)

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

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

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

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

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

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

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

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

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

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

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

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

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

HashData(ReadOnlySpan<Byte>)

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

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

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

HashData(Stream)

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

HashData(Stream, Span<Byte>)

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

HashDataAsync(Stream, CancellationToken)

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

HashDataAsync(Stream, Memory<Byte>, CancellationToken)

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

HashFinal()

파생 클래스에서 재정의된 경우 암호화 해시 알고리즘에서 마지막 데이터를 처리한 후 해시 계산을 완료합니다.

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

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

(다음에서 상속됨 HashAlgorithm)
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>, Span<Byte>, Int32)

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

TryHashFinal(Span<Byte>, Int32)

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

(다음에서 상속됨 HashAlgorithm)

명시적 인터페이스 구현

IDisposable.Dispose()

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

(다음에서 상속됨 HashAlgorithm)

적용 대상

추가 정보