MACTripleDESとは? わかりやすく解説

MACTripleDES クラス

TripleDES使用して入力データ CryptoStream の MAC (Message Authentication Code) を計算します

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

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

次のセクションコード例示しますTripleDES ハッシュ アルゴリズム使用して dataMAC計算しresult格納する例を次に示します2 番目の例は、MACTripleDES クラスの各メンバ使用する方法示してます。

例 1

この例では、定義済み定数 DATA_SIZE があることを前提にしています。

Dim data(DATA_SIZE) As Byte
Dim key(24) As Byte
       
Dim mac3des As New MACTripleDES(key)
       
Dim result As Byte() = mac3des.ComputeHash(data)
byte[] data = new byte[DATA_SIZE];
byte[] key = new byte[24];

MACTripleDES mac3des = new MACTripleDES(key);

byte[] result = mac3des.ComputeHash(data);
array<Byte>^data = gcnew array<Byte>(DATA_SIZE);
array<Byte>^key = gcnew array<Byte>(24);
MACTripleDES^ mac3des = gcnew MACTripleDES( key );
array<Byte>^result = mac3des->ComputeHash( data );
ubyte data[] = new ubyte[dataSize];
ubyte key[] = new ubyte[24];
MACTripleDES mac3des = new MACTripleDES(key);
ubyte result[] = mac3des.ComputeHash(data);

例 2

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

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 = ""

        EncodeNothing()
        EncodeMessage()
        EncodeStream()

        tbxOutput.AppendText(vbCrLf + "This sample completed "
 + _
            "successfully; press Exit to continue.")
        tbxOutput.Cursor = Cursors.Default
    End Sub
    Private Sub EncodeNothing()
        Dim macTriple As New
 MACTripleDES

        macTriple.Initialize()

        Dim key(23) As Byte
        RandomNumberGenerator.Create().GetBytes(key)
        macTriple.Key = key
        
        Dim message(1023) As Byte
        macTriple.ComputeHash(message)
        SummarizeMAC(macTriple, "MACTripleDES after initialization.")
    End Sub
    ' Compute the hash for a MACTripleDES that has transformed a byte
 array.
    Private Sub EncodeMessage()
        Dim keyData(23) As Byte
        RandomNumberGenerator.Create().GetBytes(keyData)
        Dim macTriple As New
 MACTripleDES(keyData)
        Dim message As String
 = "Encoding is fun!"
        Dim encodedMessage() As Byte
 
        encodedMessage = EncodeBytes(Encoding.ASCII.GetBytes(message))
        macTriple.ComputeHash(encodedMessage)

        SummarizeMAC(macTriple, "MACTripleDES after encoding a
 message.")
    End Sub
    ' Transform the byte array using MacTripleDES,
    ' and then summarize its properties.
    Private Function EncodeBytes(ByVal
 sourceBytes() As Byte)
        Dim currentPosition As Int16 = 0

        Dim targetBytes(1023) As Byte
        Dim sourceByteLength As Int16 = sourceBytes.Length

        ' Create an encryptor with a random key and the TripleDES
        ' class name.
        Dim key(23) As Byte
        RandomNumberGenerator.Create().GetBytes(key)
        Dim tripleDesName As String
 = "System.Security.Cryptography.TripleDES"
        Dim macTriple As New
 MACTripleDES(tripleDesName, key)

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

        Try
            ' Determine if multiple blocks can be transformed.
            If (macTriple.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 = macTriple.TransformBlock( _
                        sourceBytes, _
                        currentPosition, _
                        inputBlockSize, _
                        targetBytes, _
                        currentPosition)

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

                ' Transform the final block of bytes.
                Dim finalBytes() As Byte
 = macTriple.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

        ' Determine if the current transform can be reused.
        If (Not macTriple.CanReuseTransform)
 Then
            ' Free up any used resources.
            macTriple.Clear()
        End If

        ' Find the length of valid bytes (those without zeros).
        Dim iEnum As System.Collections.IEnumerator
        iEnum = targetBytes.GetEnumerator()

        Dim i As Int16 = 0

        While (iEnum.MoveNext())
            If (iEnum.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.
        macTriple.ComputeHash(targetBytes, 0, i)

        SummarizeMAC(macTriple, "MACTripleDES after computing
 the hash " + _
            "for the specified region of the byte array.")

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

            returnedArray(j) = targetBytes(j)
        Next j

        Return returnedArray
    End Function
    Private Sub EncodeStream()
        Dim keyData(23) As Byte
        RandomNumberGenerator.Create().GetBytes(keyData)
        Dim macTriple As New
 MACTripleDES(keyData)
        Dim filePath As String
        filePath = System.IO.Directory.GetCurrentDirectory() + "\members.txt"
        Try
            Dim fileStream As New
 FileStream( _
                filePath, _
                FileMode.Open, _
                FileAccess.Read)

            macTriple.ComputeHash(fileStream)

            SummarizeMAC(macTriple, _
                "MACTripleDES after encoding a file stream.")
        Catch ex As Exception

            WriteLine("Specified path was not found: "
 + filePath)
        End Try
    End Sub
    Private Sub SummarizeMAC( _
        ByVal macTriple As MACTripleDES, _
        ByVal description As String)
        Dim classDescription As String
 = macTriple.ToString()

        Dim computedHash() As Byte
 = macTriple.Hash

        Dim hashSize As Integer
 = macTriple.HashSize

        Dim outputBlockSize As Integer
 = macTriple.OutputBlockSize

        ' Retrieve the key used in the hash algorithm.
        Dim key() As Byte
 = macTriple.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
    ' Write the specified message and carriage return to the output
 textbox.
    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 = "MACTripleDES"
        Me.Panel2.ResumeLayout(False)
        Me.Panel1.ResumeLayout(False)
        Me.ResumeLayout(False)

    End Sub

#End Region
End Class
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Security.Cryptography;

namespace csMACTripleDES
{
    class Class1
    {
        [STAThread]
        static void Main(string[]
 args)
        {
            EncodeNothing();
            EncodeMessage();
            EncodeStream();

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

        // Compute the hash for an empty array; summarize the properties.
        private static void
 EncodeNothing()
        {
            MACTripleDES macTriple = new MACTripleDES();

            macTriple.Initialize();

            byte[] key = new byte[24];
            RandomNumberGenerator.Create().GetBytes(key);
            macTriple.Key = key;

            macTriple.ComputeHash(new byte[1024]);
            SummarizeMAC(macTriple, "MACTripleDES after initialization.");
        }

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

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

                macTriple.ComputeHash(fileStream);

                SummarizeMAC(macTriple, 
                    "MACTripleDES after encoding a file stream.");
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine("Specified path was not found: "
                    + filePath);
            }
        }

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

            string message = "Encoding is fun!";
            byte[] encodedMessage = 
                EncodeBytes(Encoding.ASCII.GetBytes(message));

            macTriple.ComputeHash(encodedMessage);

            SummarizeMAC(macTriple, "MACTripleDES after encoding a message.");
        }
        
        // Transform the byte array using MacTripleDES,
        // and 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 TripleDES
            // class name.
            byte[] key = new byte[24];
            RandomNumberGenerator.Create().GetBytes(key);
            string tripleDesName = "System.Security.Cryptography.TripleDES";
            MACTripleDES macTriple = new MACTripleDES(tripleDesName,
 key);

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

            try
            {
                // Determine if multiple blocks can be transformed.
                if (macTriple.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 = macTriple.TransformBlock(
                            sourceBytes,
                            currentPosition,
                            inputBlockSize,
                            targetBytes,
                            currentPosition);

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

                    // Transform the final block of bytes.
                    byte[] finalBytes = macTriple.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());
            }

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

            // 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.
            macTriple.ComputeHash(targetBytes,0,i);

            SummarizeMAC(macTriple, "MACTripleDES after computing the hash "
 +
                "for the specified region of the byte array.");

            // 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 MACTripleDES to the console.
        private static void
 SummarizeMAC(
            MACTripleDES macTriple, 
            string description)
        {
            string classDescription = macTriple.ToString();

            byte[] computedHash = macTriple.Hash;

            int hashSize = macTriple.HashSize;

            int outputBlockSize = macTriple.OutputBlockSize;

            // Retrieve the key used in the hash algorithm.
            byte[] key = macTriple.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 namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Collections;
using namespace System::Security::Cryptography;

namespace CryptographySample
{
    ref class DESSample
    {
    public:

        static void TestDES();

    private:
        static void EncodeNothing();
        static void EncodeStream();
        static void EncodeMessage();
        static array<Byte>^ EncodeBytes(array<Byte>^
 sourceBytes);
        static void SummarizeMAC(MACTripleDES^
 macTriple, 
            String^ description);
    };

    void DESSample::TestDES()
    {
        EncodeNothing();
        EncodeMessage();
        EncodeStream();
        Console::WriteLine("This sample completed successfully; "
            "press Enter to exit.");
        Console::ReadLine();
    }

    // Compute the hash for an empty array; summarize the properties.
    void DESSample::EncodeNothing()
    {
        MACTripleDES^ macTriple = gcnew MACTripleDES;

        macTriple->Initialize();

        array<Byte>^ key = gcnew array<Byte>(24);
        RandomNumberGenerator::Create()->GetBytes(key);
        macTriple->Key = key;
        macTriple->ComputeHash(gcnew array<Byte>(1024));
        SummarizeMAC(macTriple, "MACTripleDES after initialization.");
    }

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

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

            macTriple->ComputeHash(%fileStream);

            SummarizeMAC(macTriple, 
                "MACTripleDES after encoding a file stream.");
        }
        catch (FileNotFoundException^ ex) 
        {
            Console::WriteLine("Specified path was not found: {0}", 
                filePath);
            __assume(ex);
        }

    }


    // Compute the hash for a MACTripleDES that has transformed a
    // byte array.
    void DESSample::EncodeMessage()
    {
        Encoding^ encodingASCII = Encoding::ASCII;
        array<Byte>^ keyData = gcnew array<Byte>(24);
        RandomNumberGenerator::Create()->GetBytes(keyData);
        MACTripleDES^ macTriple = gcnew MACTripleDES(keyData);

        String^ message = "Encoding is fun!";
        array<Byte>^ encodedMessage = EncodeBytes(
            encodingASCII->GetBytes(message));
        macTriple->ComputeHash(encodedMessage);

        SummarizeMAC(macTriple, 
            "MACTripleDES after encoding a message.");
    }


    // Transform the byte array using MacTripleDES,
    // and then summarize its properties.
    array<Byte>^ DESSample::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 TripleDES
        // class name.
        array<Byte>^ key = gcnew array<Byte>(24);
        RandomNumberGenerator::Create()->GetBytes(key);
        String^ tripleName = "System.Security.Cryptography.TripleDES";
        MACTripleDES^ macTriple = gcnew MACTripleDES(tripleName, key);

        // Retrieve the block size to read the bytes.
        int inputBlockSize = macTriple->InputBlockSize;

        try
        {

            // Determine if multiple blocks can be transformed.
            if (macTriple->CanTransformMultipleBlocks)
            {
                int bytesRead = 0;
                while (sourceByteLength - currentPosition >=
 
                    inputBlockSize)
                {
                    // Transform the bytes from the currentposition
 in 
                    // the sourceBytes array, writing the bytes to the
 
                    // targetBytes array.
                    bytesRead = 
                        macTriple->TransformBlock(sourceBytes, 
                        currentPosition, inputBlockSize, targetBytes, 
                        currentPosition);
                    // Advance the current position in the
                    // sourceBytes array.
                    currentPosition += bytesRead;
                }

                // Transform the final block of bytes.
                array<Byte>^ finalBytes = 
                    macTriple->TransformFinalBlock(sourceBytes, 
                    currentPosition, sourceByteLength - 
                    currentPosition);
                // Copy the contents of the finalBytes array to the
                // targetBytes array.
                finalBytes->CopyTo(targetBytes, currentPosition);
            }
        }
        catch (ArgumentException^ ex) 
        {
            Console::WriteLine("Caught unexpected exception:{0}", ex);
        }

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

        // Find the length of valid bytes (those without zeros).
        int i = 0;
        for each (Byte byte in targetBytes)
        {
            if (byte == 0)
                break;
            i++;
        }

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

        SummarizeMAC(macTriple, "MACTripleDES after computing "
            "the hash for the specified region of the byte
 array.");

        // Create a new array with the number of valid bytes.
        array<Byte>^ returnedArray = gcnew array<Byte>(i);
        Array::Copy(targetBytes, returnedArray, i);
        return returnedArray;
    }


    // Write a summary of the specified MACTripleDES to the console.
    void DESSample::SummarizeMAC(MACTripleDES^ macTriple, 
        String^ description)
    {
        Encoding^ encASCIIEncoding = Encoding::ASCII;

        String^ classDescription = macTriple->ToString();

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

        int hashSize = macTriple->HashSize;

        int outputBlockSize = macTriple->OutputBlockSize;

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

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

using namespace CryptographySample;

int main()
{
    DESSample::TestDES();
}

//
// This sample produces the following output:
//
// **********************************
// System.Security.Cryptography.MACTripleDES
// MACTripleDES after initialization.
// ----------------------------------
// The size of the computed hash : 64
// The key used in the hash algorithm : +Lnf>j%?4?7?V???K?Jv_AcB
// The value of the computed hash : YH>|*DX;
// 
// **********************************
// System.Security.Cryptography.MACTripleDES
// MACTripleDES after computing the hash for the specified region 
// of the byte array.
// ----------------------------------
// The size of the computed hash : 64
// The key used in the hash algorithm : >
// -?h?v?tF*r`f%V?t`.jS50
// The value of the computed hash : :?9q1$b?
// 
// **********************************
// System.Security.Cryptography.MACTripleDES
// MACTripleDES after encoding a message.
// ----------------------------------
// The size of the computed hash : 64
// The key used in the hash algorithm : ?rK>~6>?xy-R? r7s,_kCP{}
// The value of the computed hash : bG?*UO?S
// 
// **********************************
// System.Security.Cryptography.MACTripleDES
// MACTripleDES after encoding a file stream.
// ----------------------------------
// The size of the computed hash : 64
// Yv)???rTY?}?T?/\FOI?D$sh algorithm :
// The value of the computed hash : K??T]QgN
// This sample completed successfully; press Enter to exit.
import System.*;
import System.IO.*;
import System.Text.*;
import System.Collections.*;
import System.Security.Cryptography.*;

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

    // Compute the hash for an empty array; summarize the properties.
    private static void
 EncodeNothing()
    {
        MACTripleDES macTriple = new MACTripleDES();

        macTriple.Initialize();

        ubyte key[] = new ubyte[24];
        RandomNumberGenerator.Create().GetBytes(key);
        macTriple.set_Key(key);
        macTriple.ComputeHash(new ubyte[1024]);
        SummarizeMAC(macTriple, "MACTripleDES after initialization.");
    } //EncodeNothing

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

        String filePath = System.IO.Directory.GetCurrentDirectory() 
            + "\\members.txt";
        try {
            FileStream fileStream = new FileStream(filePath, FileMode.Open,
 
                FileAccess.Read);
            macTriple.ComputeHash(fileStream);
            SummarizeMAC(macTriple, 
                "MACTripleDES after encoding a file stream.");
        }
        catch (FileNotFoundException ex) {
            Console.WriteLine("Specified path was not found: " + filePath);
        }
    } //EncodeStream

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

    // Transform the byte array using MacTripleDES,
    // and 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 TripleDES
        // class name.
        ubyte key[] = new ubyte[24];
        RandomNumberGenerator.Create().GetBytes(key);
        String tripleDesName = "System.Security.Cryptography.TripleDES";
        MACTripleDES macTriple = new MACTripleDES(tripleDesName,
 key);

        // Retrieve the block size to read the bytes.
        int inputBlockSize = macTriple.get_InputBlockSize();
        try {
            // Determine if multiple blocks can be transformed.
            if (macTriple.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 = macTriple.TransformBlock(sourceBytes, 
                        currentPosition, inputBlockSize, targetBytes, 
                        currentPosition);
                    // Advance the current position in the
                    // sourceBytes array.
                    currentPosition += numBytesRead;
                }
                // Transform the final block of bytes.
                ubyte finalBytes[] = macTriple.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());
        }
        // Determine if the current transform can be reused.
        if (!(macTriple.get_CanReuseTransform())) {
            // Free up any used resources.
            macTriple.Clear();
        }
        // 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.
        macTriple.ComputeHash(targetBytes, 0, i);

        SummarizeMAC(macTriple, "MACTripleDES after computing the hash "
 
            + "for the specified region of the byte array.");
        // 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 MACTripleDES to the console.
    private static void
 SummarizeMAC(MACTripleDES macTriple, 
        String description)
    {
        String classDescription = macTriple.ToString();

        ubyte computedHash[] = macTriple.get_Hash();

        int hashSize = macTriple.get_HashSize();

        int outputBlockSize = macTriple.get_OutputBlockSize();

        // Retrieve the key used in the hash algorithm.
        ubyte key[] = macTriple.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
} //Class1
継承階層継承階層
System.Object
   System.Security.Cryptography.HashAlgorithm
     System.Security.Cryptography.KeyedHashAlgorithm
      System.Security.Cryptography.MACTripleDES
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
MACTripleDES メンバ
System.Security.Cryptography 名前空間

MACTripleDES コンストラクタ ()

MACTripleDES クラス新しインスタンス初期化します。

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

public MACTripleDES ()
public:
MACTripleDES ()
public MACTripleDES ()
public function MACTripleDES ()
解説解説
使用例使用例

既定MACTripleDES コンストラクタ呼び出す方法次のコード例示します。このコード例は、MACTripleDES クラストピック取り上げているコード例一部分です。

Dim macTriple As New MACTripleDES
MACTripleDES macTriple = new MACTripleDES();
MACTripleDES^ macTriple = gcnew MACTripleDES;
MACTripleDES macTriple = new MACTripleDES();
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
MACTripleDES クラス
MACTripleDES メンバ
System.Security.Cryptography 名前空間

MACTripleDES コンストラクタ (String, Byte[])

TripleDES指定した実装使用して指定したキー データMACTripleDES クラス新しインスタンス初期化します。

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

Public Sub New ( _
    strTripleDES As String, _
    rgbKey As Byte() _
)
Dim strTripleDES As String
Dim rgbKey As Byte()

Dim instance As New MACTripleDES(strTripleDES,
 rgbKey)
public MACTripleDES (
    string strTripleDES,
    byte[] rgbKey
)
public:
MACTripleDES (
    String^ strTripleDES, 
    array<unsigned char>^ rgbKey
)
public MACTripleDES (
    String strTripleDES, 
    byte[] rgbKey
)
public function MACTripleDES (
    strTripleDES : String, 
    rgbKey : byte[]
)

パラメータ

strTripleDES

使用する TripleDES 実装の名前。

rgbKey

MACTripleDES 暗号化共有キー

例外例外
例外種類条件

ArgumentNullException

rgbKey パラメータnull 参照 (Visual Basic では Nothing) です。

CryptographicUnexpectedOperationException

strTripleDES パラメータが、TripleDES 実装有効な名前ではありません。

解説解説

strTripleDES パラメータは、TripleDES 実装タイプ表示名です。既定実装は、System.Security.Cryptography.TripleDES です。

rgbKey パラメータは、長さ16 バイトまたは 24 バイトである必要があります

使用例使用例

ランダム キーおよび TripleDES 名を使用して新しMACTripleDES生成する方法次のコード例示します。このコード例は、MACTripleDES クラストピック取り上げているコード例一部分です。

Dim key(23) As Byte
RandomNumberGenerator.Create().GetBytes(key)
Dim tripleDesName As String
 = "System.Security.Cryptography.TripleDES"
Dim macTriple As New MACTripleDES(tripleDesName,
 key)
byte[] key = new byte[24];
RandomNumberGenerator.Create().GetBytes(key);
string tripleDesName = "System.Security.Cryptography.TripleDES";
MACTripleDES macTriple = new MACTripleDES(tripleDesName, key);
array<Byte>^ key = gcnew array<Byte>(24);
RandomNumberGenerator::Create()->GetBytes(key);
String^ tripleName = "System.Security.Cryptography.TripleDES";
MACTripleDES^ macTriple = gcnew MACTripleDES(tripleName, key);
ubyte key[] = new ubyte[24];
RandomNumberGenerator.Create().GetBytes(key);
String tripleDesName = "System.Security.Cryptography.TripleDES";
MACTripleDES macTriple = new MACTripleDES(tripleDesName, key);
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
MACTripleDES クラス
MACTripleDES メンバ
System.Security.Cryptography 名前空間

MACTripleDES コンストラクタ


MACTripleDES コンストラクタ (Byte[])

キー データ指定してMACTripleDES クラス新しインスタンス初期化します。

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

Public Sub New ( _
    rgbKey As Byte() _
)
Dim rgbKey As Byte()

Dim instance As New MACTripleDES(rgbKey)
public MACTripleDES (
    byte[] rgbKey
)
public:
MACTripleDES (
    array<unsigned char>^ rgbKey
)
public MACTripleDES (
    byte[] rgbKey
)
public function MACTripleDES (
    rgbKey : byte[]
)

パラメータ

rgbKey

MACTripleDES 暗号化共有キー

例外例外
例外種類条件

ArgumentNullException

rgbKey パラメータnull 参照 (Visual Basic では Nothing) です。

解説解説

このコンストラクタは、TripleDES既定実装使用しますrgbKey パラメータは、長さ16 バイトまたは 24 バイトである必要があります

使用例使用例

ランダム キー使用して新しMACTripleDES生成する方法次のコード例示します。このコード例は、MACTripleDES クラストピック取り上げているコード例一部分です。

Dim keyData(23) As Byte
RandomNumberGenerator.Create().GetBytes(keyData)
Dim macTriple As New MACTripleDES(keyData)
byte[] keyData = new byte[24];
RandomNumberGenerator.Create().GetBytes(keyData);
MACTripleDES macTriple = new MACTripleDES(keyData);
array<Byte>^ keyData = gcnew array<Byte>(24);
RandomNumberGenerator::Create()->GetBytes(keyData);
MACTripleDES^ macTriple = gcnew MACTripleDES(keyData);
ubyte keyData[] = new ubyte[24];
RandomNumberGenerator.Create().GetBytes(keyData);
MACTripleDES macTriple = new MACTripleDES(keyData);
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
MACTripleDES クラス
MACTripleDES メンバ
System.Security.Cryptography 名前空間

MACTripleDES フィールド


プロテクト フィールドプロテクト フィールド

  名前 説明
プロテクト フィールド HashSizeValue  計算されハッシュ コードサイズビット単位表します。 ( HashAlgorithm から継承されます。)
プロテクト フィールド HashValue  計算されハッシュ コードの値を表します。 ( HashAlgorithm から継承されます。)
プロテクト フィールド KeyValue  ハッシュ アルゴリズム使用するキー。 ( KeyedHashAlgorithm から継承されます。)
プロテクト フィールド State  ハッシュ計算の状態を表します。 ( HashAlgorithm から継承されます。)
参照参照

関連項目

MACTripleDES クラス
System.Security.Cryptography 名前空間

MACTripleDES プロパティ


パブリック プロパティパブリック プロパティ

参照参照

関連項目

MACTripleDES クラス
System.Security.Cryptography 名前空間

MACTripleDES メソッド


パブリック メソッドパブリック メソッド

( プロテクト メソッド参照)
  名前 説明
パブリック メソッド Clear  HashAlgorithm クラスによって使用されているすべてのリソース解放します。 ( HashAlgorithm から継承されます。)
パブリック メソッド ComputeHash  オーバーロードされます入力データハッシュ値計算します。 ( HashAlgorithm から継承されます。)
パブリック メソッド Create  オーバーロードされますキー付きハッシュ アルゴリズムの実装インスタンス作成します。 ( KeyedHashAlgorithm から継承されます。)
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 ( Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 ( Object から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 ( Object から継承されます。)
パブリック メソッド Initialize オーバーライドされます。 MACTripleDES のインスタンス初期化します。
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 ( Object から継承されます。)
パブリック メソッド ToString  現在の Object を表す String返します。 ( Object から継承されます。)
パブリック メソッド TransformBlock  入力バイト配列指定した領域ハッシュ値計算し結果ハッシュ値出力バイト配列指定した領域コピーします。 ( HashAlgorithm から継承されます。)
パブリック メソッド TransformFinalBlock  指定したバイト配列指定した領域ハッシュ値計算します。 ( HashAlgorithm から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

MACTripleDES クラス
System.Security.Cryptography 名前空間

MACTripleDES メンバ

TripleDES使用して入力データ CryptoStream の MAC (Message Authentication Code) を計算します

MACTripleDES データ型公開されるメンバを以下の表に示します


パブリック コンストラクタパブリック コンストラクタ
プロテクト フィールドプロテクト フィールド
  名前 説明
プロテクト フィールド HashSizeValue  計算されハッシュ コードサイズビット単位表します。(HashAlgorithm から継承されます。)
プロテクト フィールド HashValue  計算されハッシュ コードの値を表します。(HashAlgorithm から継承されます。)
プロテクト フィールド KeyValue  ハッシュ アルゴリズム使用するキー。(KeyedHashAlgorithm から継承されます。)
プロテクト フィールド State  ハッシュ計算の状態を表します。(HashAlgorithm から継承されます。)
パブリック プロパティパブリック プロパティ
パブリック メソッドパブリック メソッド
( プロテクト メソッド参照)
  名前 説明
パブリック メソッド Clear  HashAlgorithm クラスによって使用されているすべてのリソース解放します。 (HashAlgorithm から継承されます。)
パブリック メソッド ComputeHash  オーバーロードされます入力データハッシュ値計算します。 (HashAlgorithm から継承されます。)
パブリック メソッド Create  オーバーロードされますキー付きハッシュ アルゴリズムの実装インスタンス作成します。 (KeyedHashAlgorithm から継承されます。)
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 (Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 (Object から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 (Object から継承されます。)
パブリック メソッド Initialize オーバーライドされますMACTripleDESインスタンス初期化します。
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 (Object から継承されます。)
パブリック メソッド ToString  現在の Object を表す String返します。 (Object から継承されます。)
パブリック メソッド TransformBlock  入力バイト配列指定した領域ハッシュ値計算し結果ハッシュ値出力バイト配列指定した領域コピーします。 (HashAlgorithm から継承されます。)
パブリック メソッド TransformFinalBlock  指定したバイト配列指定した領域ハッシュ値計算します。 (HashAlgorithm から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

MACTripleDES クラス
System.Security.Cryptography 名前空間



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

辞書ショートカット

すべての辞書の索引

「MACTripleDES」の関連用語

MACTripleDESのお隣キーワード
検索ランキング

   

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



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

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

©2024 GRAS Group, Inc.RSS