KeyedHashAlgorithm クラスとは? わかりやすく解説

KeyedHashAlgorithm クラス

キー付きハッシュ アルゴリズムすべての実装派生元となる抽象クラス表します

名前空間: System.Security.Cryptography
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

<ComVisibleAttribute(True)> _
Public MustInherit Class
 KeyedHashAlgorithm
    Inherits HashAlgorithm
Dim instance As KeyedHashAlgorithm
[ComVisibleAttribute(true)] 
public abstract class KeyedHashAlgorithm :
 HashAlgorithm
[ComVisibleAttribute(true)] 
public ref class KeyedHashAlgorithm abstract
 : public HashAlgorithm
/** @attribute ComVisibleAttribute(true) */ 
public abstract class KeyedHashAlgorithm extends
 HashAlgorithm
ComVisibleAttribute(true) 
public abstract class KeyedHashAlgorithm extends
 HashAlgorithm
解説解説
使用例使用例

KeyedHashAlgorithm クラスから派生する方法次のコード例示します

Imports System
Imports System.IO
Imports System.Text
Imports System.Collections
Imports System.Security.Cryptography

Namespace Contoso
    Public Class Form1
        Inherits System.Windows.Forms.Form

        ' Event handler for Run button.
        Private Sub Button1_Click( _
            ByVal sender As System.Object,
 _
            ByVal e As System.EventArgs) Handles
 Button1.Click

            tbxOutput.Cursor = Cursors.WaitCursor
            tbxOutput.Text = ""

            EncodeMessage()
            EncodeStream()

            ' Reset the cursor and conclude application.
            tbxOutput.AppendText(vbCrLf + "This sample completed
 " + _
                "successfully; press Exit to continue.")
            tbxOutput.Cursor = Cursors.Default
        End Sub

        ' Compute the hash for a ContosoKeyedHash that has transformed
        ' a file stream.
        Private Sub EncodeStream()
            Dim keyData(24) As Byte
            RandomNumberGenerator.Create.GetBytes(keyData)
            Dim localCrypto As New
 ContosoKeyedHash(keyData)

            Dim filePath As String
            filePath = System.IO.Directory.GetCurrentDirectory() + _
                "\members.txt"

            Try
                Dim fileStream As _
                    New FileStream(filePath, FileMode.Open, FileAccess.Read)

                localCrypto.ComputeHash(fileStream)

                SummarizeMAC(localCrypto, _
                    "ContosoKeyedHash after encoding a file stream.")
            Catch ex As FileNotFoundException
                WriteLine("Specified path was not found: "
 + filePath)
            End Try

        End Sub

        ' Compute the hash for a ContosoKeyedHash that has transformed
        ' a byte array.
        Private Sub EncodeMessage()

            Dim keyData(24) As Byte
            RandomNumberGenerator.Create().GetBytes(keyData)
            Dim localCrypto As New
 ContosoKeyedHash(keyData)

            Dim message As String
 = "Hello World."
            Dim encodedMessage() As Byte
 = _
                EncodeBytes(Encoding.ASCII.GetBytes(message))

            localCrypto.ComputeHash(encodedMessage)

            SummarizeMAC(localCrypto, _
                "ContosoKeyedHash after encoding a message.")
        End Sub

        ' Transform the byte array using ContosoKeyedHash,
        ' then summarize its properties.
        Private Function EncodeBytes(ByVal
 sourceBytes As Byte()) As
 Byte()
            Dim currentPosition As Int16 =
 0
            Dim targetBytes(1024) As Byte
            Dim sourceByteLength As Int16 =
 sourceBytes.Length

            ' Create an encryptor with a random key and the KeyedHashAlgorithm
            ' class name.
            Dim key(24) As Byte
            RandomNumberGenerator.Create().GetBytes(key)
            Dim keyedHashName As String
 
            keyedHashName = "System.Security.Cryptography.KeyedHashAlgorithm"
            Dim localCrypto As New
 ContosoKeyedHash(keyedHashName, key)

            ' Retrieve the block size to read the bytes.
            Dim inputBlockSize As Integer
 = localCrypto.InputBlockSize

            Try
                ' Determine if multiple blocks can be transformed.
                If (localCrypto.CanTransformMultipleBlocks) Then
                    Dim numBytesRead As Int16
 = 0

                    While (sourceByteLength - currentPosition
 >= _
                         inputBlockSize)

                        ' Transform the bytes from the currentposition
 in the
                        ' sourceBytes array, writing the bytes to the
 
                        ' targetBytes array.
                        numBytesRead = localCrypto.TransformBlock( _
                            sourceBytes, _
                            currentPosition, _
                            inputBlockSize, _
                            targetBytes, _
                            currentPosition)

                        ' Advance the current position in the source
 array.
                        currentPosition += numBytesRead
                    End While

                    ' Transform the final block of bytes.
                    Dim finalBytes() As Byte
                    finalBytes = localCrypto.TransformFinalBlock( _
                        sourceBytes, _
                        currentPosition, _
                        sourceByteLength - currentPosition)

                    ' Copy the contents of the finalBytes array to the
                    ' targetBytes array.
                    finalBytes.CopyTo(targetBytes, currentPosition)
                End If

            Catch ex As Exception

                WriteLine("Caught unexpected exception:"
 + _
                    ex.ToString())
            End Try

            ' Find the length of valid bytes (those without zeros).
            Dim enum1 As IEnumerator = targetBytes.GetEnumerator()
            Dim i As Int16

            While (enum1.MoveNext())
                If (enum1.Current.ToString().Equals("0"))
 Then
                    Exit While
                End If
                i = i + 1
            End While

            ' Compute the hash based on the valid bytes in the array.
            'Dim somebytes() As Byte
            'somebytes = localCrypto.ComputeHash(targetBytes, 0, i)
            localCrypto.ComputeHash(targetBytes, 0, i)

            SummarizeMAC(localCrypto, "ContosoKeyedHash after
 computing " + _
                "hash for specified region of byte array")

            ' Determine if the current transform can be reused.
            If (Not localCrypto.CanReuseTransform)
 Then

                ' Free up any used resources.
                localCrypto.Clear()

                localCrypto.Initialize()
            End If

            ' Create a new array with the number of valid bytes.
            Dim returnedArray(i) As Byte
            For j As Int16 = 0 To
 i Step 1
                returnedArray(j) = targetBytes(j)
            Next

            Return returnedArray
        End Function
        ' Write a summary of the specified ContosoKeyedHash to the 
        ' console window.
        Private Sub SummarizeMAC( _
            ByVal localCrypto As ContosoKeyedHash,
 _
            ByVal description As String)

            Dim classDescription As String
 = localCrypto.ToString()

            Dim computedHash() As Byte
 = localCrypto.Hash

            Dim hashSize As Integer
 = localCrypto.HashSize

            Dim outputBlockSize As Integer
 = localCrypto.OutputBlockSize

            ' Retrieve the key used in the hash algorithm.
            Dim key() As Byte
 = localCrypto.Key

            WriteLine(vbCrLf + "**********************************")
            WriteLine(classDescription)
            WriteLine(description)
            WriteLine("----------------------------------")
            WriteLine("The size of the computed hash : "
 + _
                hashSize.ToString())
            WriteLine("The key used in the hash algorithm : "
 + _
                Encoding.ASCII.GetString(key))
            WriteLine("The value of the computed hash : "
 + _
                Encoding.ASCII.GetString(computedHash))
        End Sub
        Private Sub WriteLine(ByVal
 Message As String)
            tbxOutput.AppendText(Message + vbCrLf)
        End Sub
        ' Event handler for Exit button.
        Private Sub Button2_Click( _
            ByVal sender As System.Object,
 _
            ByVal e As System.EventArgs) Handles
 Button2.Click

            Application.Exit()
        End Sub
#Region " Windows Form Designer generated code "

        Public Sub New()
            MyBase.New()

            'This call is required by the Windows Form Designer.
            InitializeComponent()

            'Add any initialization after the InitializeComponent()
 call

        End Sub

        'Form overrides dispose to clean up the component list.
        Protected Overloads Overrides
 Sub Dispose(ByVal disposing As
 Boolean)
            If disposing Then
                If Not (components Is
 Nothing) Then
                    components.Dispose()
                End If
            End If
            MyBase.Dispose(disposing)
        End Sub

        'Required by the Windows Form Designer
        Private components As System.ComponentModel.IContainer

        'NOTE:The following procedure is required by the Windows Form
 Designer
        'It can be modified using the Windows Form Designer.  
        'Do not modify it using the code editor.
        Friend WithEvents Panel2 As
 System.Windows.Forms.Panel
        Friend WithEvents Panel1 As
 System.Windows.Forms.Panel
        Friend WithEvents Button1 As
 System.Windows.Forms.Button
        Friend WithEvents Button2 As
 System.Windows.Forms.Button
        Friend WithEvents tbxOutput As
 System.Windows.Forms.RichTextBox
        <System.Diagnostics.DebuggerStepThrough()> _
        Private Sub InitializeComponent()
            Me.Panel2 = New System.Windows.Forms.Panel
            Me.Button1 = New System.Windows.Forms.Button
            Me.Button2 = New System.Windows.Forms.Button
            Me.Panel1 = New System.Windows.Forms.Panel
            Me.tbxOutput = New System.Windows.Forms.RichTextBox
            Me.Panel2.SuspendLayout()
            Me.Panel1.SuspendLayout()
            Me.SuspendLayout()
            '
            'Panel2
            '
            Me.Panel2.Controls.Add(Me.Button1)
            Me.Panel2.Controls.Add(Me.Button2)
            Me.Panel2.Dock = System.Windows.Forms.DockStyle.Bottom
            Me.Panel2.DockPadding.All = 20
            Me.Panel2.Location = New System.Drawing.Point(0,
 320)
            Me.Panel2.Name = "Panel2"
            Me.Panel2.Size = New System.Drawing.Size(616,
 64)
            Me.Panel2.TabIndex = 1
            '
            'Button1
            '
            Me.Button1.Dock = System.Windows.Forms.DockStyle.Right
            Me.Button1.Font = New System.Drawing.Font(
 _
                "Microsoft Sans Serif", _
                9.0!, _
                System.Drawing.FontStyle.Regular, _
                System.Drawing.GraphicsUnit.Point, _
                CType(0, Byte))
            Me.Button1.Location = New System.Drawing.Point(446,
 20)
            Me.Button1.Name = "Button1"
            Me.Button1.Size = New System.Drawing.Size(75,
 24)
            Me.Button1.TabIndex = 2
            Me.Button1.Text = "&Run"
            '
            'Button2
            '
            Me.Button2.Dock = System.Windows.Forms.DockStyle.Right
            Me.Button2.Font = New System.Drawing.Font(
 _
                "Microsoft Sans Serif", _
                9.0!, _
                System.Drawing.FontStyle.Regular, _
                System.Drawing.GraphicsUnit.Point, _
                CType(0, Byte))
            Me.Button2.Location = New System.Drawing.Point(521,
 20)
            Me.Button2.Name = "Button2"
            Me.Button2.Size = New System.Drawing.Size(75,
 24)
            Me.Button2.TabIndex = 3
            Me.Button2.Text = "E&xit"
            '
            'Panel1
            '
            Me.Panel1.Controls.Add(Me.tbxOutput)
            Me.Panel1.Dock = System.Windows.Forms.DockStyle.Fill
            Me.Panel1.DockPadding.All = 20
            Me.Panel1.Location = New System.Drawing.Point(0,
 0)
            Me.Panel1.Name = "Panel1"
            Me.Panel1.Size = New System.Drawing.Size(616,
 320)
            Me.Panel1.TabIndex = 2
            '
            'tbxOutput
            '
            Me.tbxOutput.AccessibleDescription = _
                "Displays output from application."
            Me.tbxOutput.AccessibleName = "Output
 textbox."
            Me.tbxOutput.Dock = System.Windows.Forms.DockStyle.Fill
            Me.tbxOutput.Location = New System.Drawing.Point(20,
 20)
            Me.tbxOutput.Name = "tbxOutput"
            Me.tbxOutput.Size = New System.Drawing.Size(576,
 280)
            Me.tbxOutput.TabIndex = 1
            Me.tbxOutput.Text = "Click the
 Run button to run the application."
            '
            'Form1
            '
            Me.AutoScaleBaseSize = New System.Drawing.Size(6,
 15)
            Me.ClientSize = New System.Drawing.Size(616,
 384)
            Me.Controls.Add(Me.Panel1)
            Me.Controls.Add(Me.Panel2)
            Me.Name = "Form1"
            Me.Text = "KeyedHashAlgorithm"
            Me.Panel2.ResumeLayout(False)
            Me.Panel1.ResumeLayout(False)
            Me.ResumeLayout(False)
        End Sub
#End Region
    End Class
End Namespace
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Security.Cryptography;

namespace Contoso
{
    class EncodeWithContoso
    {
        [STAThread]
        static void Main(string[]
 args)
        {
            EncodeMessage();
            EncodeStream();

            Console.WriteLine("This sample completed successfully; " +
 
                "press Enter to exit");
            Console.ReadLine();
        }

        // Compute the hash for a ContosoKeyedHash that has transformed
 a
        // file stream.
        private static void
 EncodeStream()
        {
            byte[] keyData = new byte[24];
            RandomNumberGenerator.Create().GetBytes(keyData);
            ContosoKeyedHash localCrypto = new ContosoKeyedHash(keyData);

            string filePath = (System.IO.Directory.GetCurrentDirectory()
 +
                "\\members.txt");
            try
            {
                FileStream fileStream =
                    new FileStream(filePath, FileMode.Open, FileAccess.Read);

                localCrypto.ComputeHash(fileStream);

                SummarizeMAC(localCrypto, 
                    "ContosoKeyedHash after encoding a file stream.");
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("The specified path was not found: "
 +
                    filePath);
            }
        }

        // Compute the hash for a ContosoKeyedHash that has transformed
        // a byte array.
        private static void
 EncodeMessage()
        {
            byte[] keyData = new byte[24];
            RandomNumberGenerator.Create().GetBytes(keyData);
            ContosoKeyedHash localCrypto = new ContosoKeyedHash(keyData);

            string message = "Hello World.";
            byte[] encodedMessage = 
                EncodeBytes(Encoding.ASCII.GetBytes(message));

            localCrypto.ComputeHash(encodedMessage);

            SummarizeMAC(localCrypto, 
                "ContosoKeyedHash after encoding a message.");
        }
        
        // Transform the byte array using ContosoKeyedHash,
        // then summarize its properties.
        private static byte[] EncodeBytes(byte[]
 sourceBytes)
        {
            int currentPosition = 0;
            byte[] targetBytes = new byte[1024];
            int sourceByteLength = sourceBytes.Length;

            // Create an encryptor with a random key and the
            // KeyedHashAlgorithm class name.
            byte[] key = new byte[24];
            RandomNumberGenerator.Create().GetBytes(key);
            string keyedHashName = 
                "System.Security.Cryptography.KeyedHashAlgorithm";
            ContosoKeyedHash localCrypto = 
                new ContosoKeyedHash(keyedHashName, key);

            // Retrieve the block size to read the bytes.
            int inputBlockSize = localCrypto.InputBlockSize;

            try
            {
                // Determine if multiple blocks can be transformed.
                if (localCrypto.CanTransformMultipleBlocks)
                {
                    int numBytesRead = 0;
                    while (sourceByteLength - currentPosition
 >= 
                        inputBlockSize)
                    {
                        // Transform the bytes from the currentposition
 in the
                        // sourceBytes array, writing the bytes to the
 
                        // targetBytes array.
                        numBytesRead = localCrypto.TransformBlock(
                            sourceBytes,
                            currentPosition,
                            inputBlockSize,
                            targetBytes,
                            currentPosition);

                        // Advance the current position in the source
 array.
                        currentPosition += numBytesRead;
                    }

                    // Transform the final block of bytes.
                    byte[] finalBytes = localCrypto.TransformFinalBlock(
                        sourceBytes,
                        currentPosition,
                        sourceByteLength - currentPosition);

                    // Copy the contents of the finalBytes array to
 the
                    // targetBytes array.
                    finalBytes.CopyTo(targetBytes,currentPosition);
                }

            }
            catch(Exception ex)
            {
                Console.WriteLine("Caught unexpected exception:" + 
                    ex.ToString());
            }

            // Find the length of valid bytes (those without zeros).
            IEnumerator enum1 = targetBytes.GetEnumerator();
            int i = 0;
            while (enum1.MoveNext())
            {
                if (enum1.Current.ToString().Equals("0"))
                {
                    break;
                } 
                i++;
            }

            // Compute the hash based on the valid bytes in the array.
            localCrypto.ComputeHash(targetBytes,0,i);

            SummarizeMAC(localCrypto, "ContosoKeyedHash after computing "
 +
                "hash for specified region of byte array");

            // Determine if the current transform can be reused.
            if (!localCrypto.CanReuseTransform)
            {
                // Free up any used resources.
                localCrypto.Clear();

                localCrypto.Initialize();
            }

            // Create a new array with the number of valid bytes.
            byte[] returnedArray = new byte[i];
            for (int j=0; j<i; j++) 
            {
                returnedArray[j] = targetBytes[j];
            }

            return returnedArray;
        }
        
        // Write a summary of the specified ContosoKeyedHash to the
        // console window.
        private static void
 SummarizeMAC(
            ContosoKeyedHash localCrypto,
            string description)
        {
            string classDescription = localCrypto.ToString();

            byte[] computedHash = localCrypto.Hash;

            int hashSize = localCrypto.HashSize;

            int outputBlockSize = localCrypto.OutputBlockSize;

            // Retrieve the key used in the hash algorithm.
            byte[] key = localCrypto.Key;

            Console.WriteLine("\n**********************************");
            Console.WriteLine(classDescription);
            Console.WriteLine(description);
            Console.WriteLine("----------------------------------");
            Console.WriteLine("The size of the computed hash : " + hashSize);
            Console.WriteLine("The key used in the hash algorithm
 : " + 
                Encoding.ASCII.GetString(key));
            Console.WriteLine("The value of the computed hash : " + 
                Encoding.ASCII.GetString(computedHash));
        }
    }
}
#using <System.dll>
#using "contosokeyedhash.dll"
using namespace Contoso;
using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Collections;
using namespace System::Security::Cryptography;

namespace Contoso
{
   ref class EncodeWithContoso
   {
   public:
      [STAThread]
      static void Main()
      {
         EncodeMessage();
         EncodeStream();
         Console::WriteLine( L"This sample completed successfully; "
         L"press Enter to exit" );
         Console::ReadLine();
      }

   private:
      // Compute the hash for a ContosoKeyedHash that has transformed
 a
      // file stream.
      static void EncodeStream()
      {
         array<Byte>^keyData = gcnew array<Byte>(24);
         RandomNumberGenerator::Create()->GetBytes( keyData );
         ContosoKeyedHash^ localCrypto = gcnew ContosoKeyedHash( keyData );

         String^ filePath = (String::Concat(
            System::IO::Directory::GetCurrentDirectory(), L"\\members.txt"
 ));
         try
         {
            FileStream^ fileStream = gcnew FileStream(
               filePath,FileMode::Open,FileAccess::Read );
            localCrypto->ComputeHash( fileStream );

            SummarizeMAC( localCrypto,
               L"ContosoKeyedHash after encoding a file stream." );
         }
         catch ( FileNotFoundException^ ) 
         {
            Console::WriteLine( L"The specified path was not found: {0}",
 filePath );
         }
      }

      // Compute the hash for a ContosoKeyedHash that has transformed
      // a byte array.
      static void EncodeMessage()
      {
         array<Byte>^ keyData = gcnew array<Byte>(24);
         RandomNumberGenerator::Create()->GetBytes( keyData );
         ContosoKeyedHash^ localCrypto = gcnew ContosoKeyedHash( keyData );
         
         String^ message = L"Hello World.";
         array<Byte>^ encodedMessage = EncodeBytes(
            Encoding::ASCII->GetBytes( message ) );
         localCrypto->ComputeHash( encodedMessage );
         
         SummarizeMAC( localCrypto, L"ContosoKeyedHash after encoding a message."
 );
      }


      // Transform the byte array using ContosoKeyedHash,
      // then summarize its properties.
      static array<Byte>^ EncodeBytes( array<Byte>^
 sourceBytes )
      {
         int currentPosition = 0;
         array<Byte>^targetBytes = gcnew array<Byte>(1024);
         int sourceByteLength = sourceBytes->Length;
         
         // Create an encryptor with a random key and the
         // KeyedHashAlgorithm class name.
         array<Byte>^ key = gcnew array<Byte>(24);
         RandomNumberGenerator::Create()->GetBytes( key );
         String^ keyedHashName = L"System.Security.Cryptography.KeyedHashAlgorithm";
         ContosoKeyedHash^ localCrypto = gcnew ContosoKeyedHash( keyedHashName,key
 );
         
         // Retrieve the block size to read the bytes.
         int inputBlockSize = localCrypto->InputBlockSize;

         try
         {
            // Determine if multiple blocks can be transformed.
            if ( localCrypto->CanTransformMultipleBlocks )
            {
               int numBytesRead = 0;
               while ( sourceByteLength - currentPosition >=
 inputBlockSize )
               {
                  // Transform the bytes from the currentposition in
 the
                  // sourceBytes array, writing the bytes to the
                  // targetBytes array.
                  numBytesRead = localCrypto->TransformBlock(
                     sourceBytes,
                     currentPosition,
                     inputBlockSize,
                     targetBytes,
                     currentPosition );

                  // Advance the current position in the source array.
                  currentPosition += numBytesRead;
               }
               
               // Transform the final block of bytes.
               array<Byte>^ finalBytes = localCrypto->TransformFinalBlock(
                  sourceBytes,
                  currentPosition,
                  sourceByteLength - currentPosition );

               // Copy the contents of the finalBytes array to the
               // targetBytes array.
               finalBytes->CopyTo( targetBytes, currentPosition );
            }
         }
         catch ( Exception^ ex ) 
         {
            Console::WriteLine( L"Caught unexpected exception:{0}",
               ex->ToString() );
         }
         
         // Find the length of valid bytes (those without zeros).
         IEnumerator^ enum1 = targetBytes->GetEnumerator();
         int i = 0;
         while ( enum1->MoveNext() )
         {
            if ( enum1->Current->ToString()->Equals(
 L"0" ) )
            {
               break;
            }

            i++;
         }
         
         // Compute the hash based on the valid bytes in the array.
         localCrypto->ComputeHash( targetBytes, 0, i );

         SummarizeMAC( localCrypto, L"ContosoKeyedHash after computing "
         L"hash for specified region of byte array"
 );
         
         // Determine if the current transform can be reused.
         if (  !localCrypto->CanReuseTransform )
         {
            // Free up any used resources.
            localCrypto->Clear();

            localCrypto->Initialize();
         }
         
         // Create a new array with the number of valid bytes.
         array<Byte>^returnedArray = gcnew array<Byte>(i);
         for ( int j = 0; j < i; j++ )
         {
            returnedArray[ j ] = targetBytes[ j ];

         }
         return returnedArray;
      }

      // Write a summary of the specified ContosoKeyedHash to the
      // console window.
      static void SummarizeMAC( ContosoKeyedHash^
 localCrypto,
         String^ description )
      {
         String^ classDescription = localCrypto->ToString();

         array<Byte>^computedHash = localCrypto->Hash;

         int hashSize = localCrypto->HashSize;

         int outputBlockSize = localCrypto->OutputBlockSize;

         // Retrieve the key used in the hash algorithm.
         array<Byte>^key = localCrypto->Key;

         Console::WriteLine( L"\n**********************************" );
         Console::WriteLine( classDescription );
         Console::WriteLine( description );
         Console::WriteLine( L"----------------------------------" );
         Console::WriteLine( L"The size of the computed hash : {0}",
            hashSize );
         Console::WriteLine( L"The key used in the hash algorithm
 : {0}",
            Encoding::ASCII->GetString( key ) );
         Console::WriteLine( L"The value of the computed hash : {0}",
            Encoding::ASCII->GetString( computedHash ) );
      }
   };
}

int main()
{
   EncodeWithContoso::Main();
}
import System.*;
import System.IO.*;
import System.Text.*;
import System.Collections.*;
import System.Security.Cryptography.*;

class EncodeWithContoso
{
    /** @attribute STAThread()
     */
    public static void main(String[]
 args)
    {
        EncodeMessage();
        EncodeStream();
        Console.WriteLine("This sample completed successfully; " 
            + "press Enter to exit");
        Console.ReadLine();
    } //main

    // Compute the hash for a ContosoKeyedHash that has transformed
 a
    // file stream.
    private static void
 EncodeStream()
    {
        ubyte keyData[] = new ubyte[24];
        RandomNumberGenerator.Create().GetBytes(keyData);
        ContosoKeyedHash localCrypto = new ContosoKeyedHash(keyData);
        String filePath = System.IO.Directory.GetCurrentDirectory() 
            + "\\members.txt";
        try {
            FileStream fileStream = new FileStream(filePath, FileMode.Open,
 
                FileAccess.Read);
            localCrypto.ComputeHash(fileStream);
            SummarizeMAC(localCrypto, 
                "ContosoKeyedHash after encoding a file stream.");
        }
        catch (FileNotFoundException exp) {
            Console.WriteLine("The specified path was not found: " + filePath);
        }
    } //EncodeStream

    // Compute the hash for a ContosoKeyedHash that has transformed
    // a byte array.
    private static void
 EncodeMessage()
    {
        ubyte keyData[] = new ubyte[24];
        RandomNumberGenerator.Create().GetBytes(keyData);
        ContosoKeyedHash localCrypto = new ContosoKeyedHash(keyData);
        String message = "Hello World.";
        ubyte encodedMessage[] = EncodeBytes(Encoding.get_ASCII().
            GetBytes(message));
        localCrypto.ComputeHash(encodedMessage);
        SummarizeMAC(localCrypto, 
            "ContosoKeyedHash after encoding a message.");
    } //EncodeMessage

    // Transform the byte array using ContosoKeyedHash,
    // then summarize its properties.
    private static ubyte[] EncodeBytes(ubyte
 sourceBytes[])
    {
        int currentPosition = 0;
        ubyte targetBytes[] = new ubyte[1024];
        int sourceByteLength = sourceBytes.get_Length();
        // Create an encryptor with a random key and the
        // KeyedHashAlgorithm class name.
        ubyte key[] = new ubyte[24];
        RandomNumberGenerator.Create().GetBytes(key);
        String keyedHashName = "System.Security.Cryptography.KeyedHashAlgorithm";
        ContosoKeyedHash localCrypto = new ContosoKeyedHash(keyedHashName,
 key);
        // Retrieve the block size to read the bytes.
        int inputBlockSize = localCrypto.get_InputBlockSize();
        try {
            // Determine if multiple blocks can be transformed.
            if (localCrypto.get_CanTransformMultipleBlocks())
 {
                int numBytesRead = 0;
                while (sourceByteLength - currentPosition >=
 inputBlockSize) {
                    // Transform the bytes from the currentposition in
 the
                    // sourceBytes array, writing the bytes to the 
                    // targetBytes array.
                    numBytesRead = localCrypto.TransformBlock(sourceBytes, 
                        currentPosition, inputBlockSize, targetBytes, 
                        currentPosition);
                    // Advance the current position in the source array.
                    currentPosition += numBytesRead;
                }
                
                // Transform the final block of bytes.
                ubyte finalBytes[] = localCrypto.TransformFinalBlock(sourceBytes,
 
                      currentPosition, sourceByteLength - currentPosition);

                // Copy the contents of the finalBytes array to the
                // targetBytes array.
                finalBytes.CopyTo(targetBytes, currentPosition);
            }
        }
        catch (System.Exception ex) {
            Console.WriteLine("Caught unexpected exception:" + ex.ToString());
        }
        // Find the length of valid bytes (those without zeros).
        IEnumerator enum1 = targetBytes.GetEnumerator();
        int i = 0;
        while (enum1.MoveNext()) {
            if (enum1.get_Current().ToString().Equals("0"))
 {
                break;
            }
            i++;
        }
        // Compute the hash based on the valid bytes in the array.
        localCrypto.ComputeHash(targetBytes, 0, i);

        SummarizeMAC(localCrypto, "ContosoKeyedHash after computing " 
            + "hash for specified region of byte array");
        
        // Determine if the current transform can be reused.
        if (!(localCrypto.get_CanReuseTransform())) {
            // Free up any used resources.
            localCrypto.Clear();

            localCrypto.Initialize();
        }
        // Create a new array with the number of valid bytes.
        ubyte returnedArray[] = new ubyte[i];
        for (int j = 0; j < i; j++) {
            returnedArray.set_Item(j, targetBytes.get_Item(j));
        }
        return returnedArray;
    } //EncodeBytes

    // Write a summary of the specified ContosoKeyedHash to the
    // console window.
    private static void
 SummarizeMAC(ContosoKeyedHash localCrypto, 
        String description)
    {
        String classDescription = localCrypto.ToString();

        ubyte computedHash[] = localCrypto.get_Hash();

        int hashSize = localCrypto.get_HashSize();

        int outputBlockSize = localCrypto.get_OutputBlockSize();

        // Retrieve the key used in the hash algorithm.
        ubyte key[] = localCrypto.get_Key();

        Console.WriteLine("\n**********************************");
        Console.WriteLine(classDescription);
        Console.WriteLine(description);
        Console.WriteLine("----------------------------------");
        Console.WriteLine("The size of the computed hash : " + hashSize);
        Console.WriteLine("The key used in the hash algorithm
 : " 
            + Encoding.get_ASCII().GetString(key));
        Console.WriteLine("The value of the computed hash : " 
            + Encoding.get_ASCII().GetString(computedHash));
    } //SummarizeMAC
} //EncodeWithContoso
Imports System
Imports System.Security.Cryptography

Namespace Contoso
    Public Class ContosoKeyedHash
        Inherits KeyedHashAlgorithm

        Dim keyedCrypto As KeyedHashAlgorithm

        Public Sub New(ByVal
 rgbKey() As Byte)
            Me.New("System.Security.Cryptography.KeyedHashAlgorithm",
 rgbKey)
        End Sub

        Public Sub New(ByVal
 keyedHashName As String, ByVal
 rgbKey() As Byte)
            ' Make sure we know which algorithm to use
            If (Not rgbKey Is
 Nothing) Then
                KeyValue = rgbKey
                HashSizeValue = 160

                ' Create a KeyedHashAlgorithm encryptor
                If (keyedHashName Is Nothing)
 Then
                    keyedCrypto = KeyedHashAlgorithm.Create()
                Else
                    keyedCrypto = KeyedHashAlgorithm.Create(keyedHashName)
                End If

                '                keyedCrypto.Key = rgbKey
            Else
                Throw New ArgumentNullException("rgbKey")
            End If
        End Sub

        ' Override abstract methods from the HashAlgorithm class.
        Public Overrides Sub
 Initialize()

        End Sub

        ' Override the Key property to use the local key from keyedCrypto.
        Public Overrides Property
 Key() As Byte()
            Get
                Return CType(keyedCrypto.Key.Clone(), Byte())
            End Get
            Set(ByVal Value As
 Byte())
                keyedCrypto.Key = CType(Value.Clone(), Byte())
            End Set
        End Property

        Protected Overrides Sub
 HashCore( _
            ByVal rgbData() As Byte,
 _
            ByVal ibStart As Integer,
 _
            ByVal cbSize As Integer)

        End Sub
        Protected Overrides Function
 HashFinal() As Byte()
            Dim returnBytes(0) As Byte
            Return returnBytes
        End Function
    End Class
End Namespace

using System;
using System.Security.Cryptography;

namespace Contoso
{
    class ContosoKeyedHash : KeyedHashAlgorithm
    {
        private KeyedHashAlgorithm keyedCrypto;

        public ContosoKeyedHash(byte[] rgbKey) 
            : this("System.Security.Cryptography.KeyedHashAlgorithm",
 rgbKey)
        {

        }

        public ContosoKeyedHash(String keyedHashName, byte[] rgbKey)
        {
            // Make sure we know which algorithm to use
            if (rgbKey != null) 
            {
                KeyValue = rgbKey;
                HashSizeValue = 160;
                
                // Create a KeyedHashAlgorithm encryptor
                if (keyedHashName == null)
 
                {
                    keyedCrypto = KeyedHashAlgorithm.Create();
                } 
                else 
                {
                    keyedCrypto = KeyedHashAlgorithm.Create(keyedHashName);
                }
            }
            else 
            {
                throw new ArgumentNullException("rgbKey");
            }
        }

        // Override abstract methods from the HashAlgorithm class.
        public override void Initialize() {}


        public override byte[] Key
        {
            get
            {
                return (byte[]) keyedCrypto.Key.Clone();
            }
            set
            {
                keyedCrypto.Key = (byte[]) value.Clone();
            }
        }

        protected override void HashCore(
            byte[] rgbData, 
            int ibStart, 
            int cbSize)
        {

        }
        protected override byte[] HashFinal()
        {
            return new byte[0];
        }
    }
}
using namespace System;
using namespace System::Security::Cryptography;

namespace Contoso
{
   public ref class ContosoKeyedHash: public
 KeyedHashAlgorithm
   {
   private:
      KeyedHashAlgorithm^ keyedCrypto;

   public:
      ContosoKeyedHash( array<Byte>^ rgbKey )
      {
         Init( L"System.Security.Cryptography.KeyedHashAlgorithm", rgbKey
 );
      }

      ContosoKeyedHash( String^ keyedHashName, array<Byte>^ rgbKey )
      {
         Init( keyedHashName, rgbKey );
      }

      void Init( String^ keyedHashName, array<Byte>^ rgbKey
 )
      {
         // Make sure we know which algorithm to use
         if ( rgbKey != nullptr )
         {
            KeyValue = rgbKey;
            HashSizeValue = 160;
            
            // Create a KeyedHashAlgorithm encryptor
            if ( keyedHashName == nullptr )
            {
               
               keyedCrypto = KeyedHashAlgorithm::Create();
            }
            else
            {
               keyedCrypto = KeyedHashAlgorithm::Create( keyedHashName );
            }
         }
         else
         {
            throw gcnew ArgumentNullException( L"rgbKey" );
         }
      }

      // Override abstract methods from the HashAlgorithm class.
      virtual void Initialize() override {}

      property array<Byte>^ Key 
      {
         virtual array<Byte>^ get() override
         {
            return dynamic_cast<array<Byte>^>(keyedCrypto->Key->Clone());
         }

         virtual void set( array<Byte>^value
 ) override
         {
            keyedCrypto->Key = dynamic_cast<array<Byte>^>(value->Clone());
         }
      }

   protected:
      virtual void HashCore( array<Byte>^ , int
 /*ibStart*/, int /*cbSize*/ ) override {}

      virtual array<Byte>^ HashFinal() override
      {
         return gcnew array<Byte>(0);
      }
   };
}
import System.*;
import System.Security.Cryptography.*;

class ContosoKeyedHash extends KeyedHashAlgorithm
{
    private KeyedHashAlgorithm keyedCrypto;

    public ContosoKeyedHash(ubyte rgbKey[])
    {
        this("System.Security.Cryptography.KeyedHashAlgorithm",
 rgbKey);
    } //ContosoKeyedHash

    public ContosoKeyedHash(String keyedHashName, ubyte rgbKey[])
    {
        // Make sure we know which algorithm to use
        if (rgbKey != null) {
            KeyValue = rgbKey;
            HashSizeValue = 160;
            // Create a KeyedHashAlgorithm encryptor
            if (keyedHashName == null) {
                keyedCrypto = KeyedHashAlgorithm.Create();
            }
            else {
                keyedCrypto = KeyedHashAlgorithm.Create(keyedHashName);
            }
        } 
        else {
            throw new ArgumentNullException("rgbKey");
        }
    } //ContosoKeyedHash

    // Override abstract methods from the HashAlgorithm class.
    public void Initialize()
    {
    } //Initialize 

    /** @property 
     */
    public ubyte[] get_Key()
    {
        return (ubyte[])keyedCrypto.get_Key().Clone();
    } //get_Key

    /** @property 
     */
    public void set_Key(ubyte value[])
    {
        keyedCrypto.set_Key((ubyte[])(value.Clone()));
    } //set_Key

    protected void HashCore(ubyte rgbData[],
 int ibStart, int cbSize)
    {
    } //HashCore

    protected ubyte[] HashFinal()
    {
        return new ubyte[0];
    } //HashFinal
} //ContosoKeyedHash
継承階層継承階層
System.Object
   System.Security.Cryptography.HashAlgorithm
    System.Security.Cryptography.KeyedHashAlgorithm
       System.Security.Cryptography.HMAC
       System.Security.Cryptography.MACTripleDES
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「KeyedHashAlgorithm クラス」の関連用語

KeyedHashAlgorithm クラスのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



KeyedHashAlgorithm クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2025 Microsoft.All rights reserved.

©2025 GRAS Group, Inc.RSS