다음을 통해 공유


TripleDES.Create 메서드

정의

TripleDES 알고리즘을 수행할 암호화 개체의 인스턴스를 만듭니다.

오버로드

Create()

TripleDES 알고리즘을 수행할 암호화 개체의 인스턴스를 만듭니다.

Create(String)
사용되지 않음.

암호화 개체의 인스턴스를 만들어 지정된 방식으로 TripleDES 알고리즘을 구현합니다.

Create()

Source:
TripleDES.cs
Source:
TripleDES.cs
Source:
TripleDES.cs

TripleDES 알고리즘을 수행할 암호화 개체의 인스턴스를 만듭니다.

public:
 static System::Security::Cryptography::TripleDES ^ Create();
public static System.Security.Cryptography.TripleDES Create ();
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static System.Security.Cryptography.TripleDES Create ();
static member Create : unit -> System.Security.Cryptography.TripleDES
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member Create : unit -> System.Security.Cryptography.TripleDES
Public Shared Function Create () As TripleDES

반환

암호화 개체의 인스턴스입니다.

특성

예제

다음 코드 예제에서는 만들고 파일에서 TripleDES 데이터를 암호화 하 고 암호를 해독 하는 개체를 사용 하는 방법을 보여 입니다.

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

void EncryptTextToFile(String^ text, String^ path, array<Byte>^ key, array<Byte>^ iv);
String^ DecryptTextFromFile(String^ path, array<Byte>^ key, array<Byte>^ iv);

int main()
{
    try
    {
        array<Byte>^ key;
        array<Byte>^ iv;

        // Create a new TripleDES object to generate a random key
        // and initialization vector (IV).
        {
            TripleDES^ tripleDes;

            try
            {
                tripleDes = TripleDES::Create();
                key = tripleDes->Key;
                iv = tripleDes->IV;
            }
            finally
            {
                delete tripleDes;
            }
        }

        // Create a string to encrypt.
        String^ original = "Here is some data to encrypt.";
        // The name/path of the file to write.
        String^ filename = "CText.enc";

        // Encrypt the string to a file.
        EncryptTextToFile(original, filename, key, iv);

        // Decrypt the file back to a string.
        String^ decrypted = DecryptTextFromFile(filename, key, iv);

        // Display the decrypted string to the console.
        Console::WriteLine(decrypted);
    }
    catch (Exception^ e)
    {
        Console::WriteLine(e->Message);
    }
}

void EncryptTextToFile(String^ text, String^ path, array<Byte>^ key, array<Byte>^ iv)
{
    FileStream^ fStream = nullptr;
    TripleDES^ tripleDes = nullptr;
    ICryptoTransform^ encryptor = nullptr;
    CryptoStream^ cStream = nullptr;

    try
    {
        // Create or open the specified file.
        fStream = File::Open(path, FileMode::Create);
        // Create a new TripleDES object.
        tripleDes = TripleDES::Create();
        // Create a TripleDES encryptor from the key and IV
        encryptor = tripleDes->CreateEncryptor(key, iv);
        // Create a CryptoStream using the FileStream and encryptor
        cStream = gcnew CryptoStream(fStream, encryptor, CryptoStreamMode::Write);

        // Convert the provided string to a byte array.
        array<Byte>^ toEncrypt = Encoding::UTF8->GetBytes(text);

        // Write the byte array to the crypto stream.
        cStream->Write(toEncrypt, 0, toEncrypt->Length);
    }
    catch (CryptographicException^ e)
    {
        Console::WriteLine("A Cryptographic error occurred: {0}", e->Message);
        throw;
    }
    finally
    {
        if (cStream != nullptr)
            delete cStream;

        if (encryptor != nullptr)
            delete encryptor;

        if (tripleDes != nullptr)
            delete tripleDes;

        if (fStream != nullptr)
            delete fStream;
    }
}

String^ DecryptTextFromFile(String^ path, array<Byte>^ key, array<Byte>^ iv)
{
    FileStream^ fStream = nullptr;
    TripleDES^ tripleDes = nullptr;
    ICryptoTransform^ decryptor = nullptr;
    CryptoStream^ cStream = nullptr;
    StreamReader^ reader = nullptr;

    try
    {
        // Open the specified file
        fStream = File::OpenRead(path);
        // Create a new TripleDES object.
        tripleDes = TripleDES::Create();
        // Create a TripleDES decryptor from the key and IV
        decryptor = tripleDes->CreateDecryptor(key, iv);
        // Create a CryptoStream using the FileStream and decryptor
        cStream = gcnew CryptoStream(fStream, decryptor, CryptoStreamMode::Read);
        // Create a StreamReader to turn the bytes back into text
        reader = gcnew StreamReader(cStream, Encoding::UTF8);

        // Read back all of the text from the StreamReader, which receives
        // the decrypted bytes from the CryptoStream, which receives the
        // encrypted bytes from the FileStream.
        return reader->ReadToEnd();
    }
    catch (CryptographicException^ e)
    {
        Console::WriteLine("A Cryptographic error occurred: {0}", e->Message);
        throw;
    }
    finally
    {
        if (cStream != nullptr)
            delete cStream;

        if (decryptor != nullptr)
            delete decryptor;

        if (tripleDes != nullptr)
            delete tripleDes;

        if (fStream != nullptr)
            delete fStream;
    }
}
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

class TripleDESSample
{
    static void Main()
    {
        try
        {
            byte[] key;
            byte[] iv;

            // Create a new TripleDES object to generate a random key
            // and initialization vector (IV).
            using (TripleDES tripleDes = TripleDES.Create())
            {
                key = tripleDes.Key;
                iv = tripleDes.IV;
            }

            // Create a string to encrypt.
            string original = "Here is some data to encrypt.";
            // The name/path of the file to write.
            string filename = "CText.enc";

            // Encrypt the string to a file.
            EncryptTextToFile(original, filename, key, iv);

            // Decrypt the file back to a string.
            string decrypted = DecryptTextFromFile(filename, key, iv);

            // Display the decrypted string to the console.
            Console.WriteLine(decrypted);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

    public static void EncryptTextToFile(string text, string path, byte[] key, byte[] iv)
    {
        try
        {
            // Create or open the specified file.
            using (FileStream fStream = File.Open(path, FileMode.Create))
            // Create a new TripleDES object.
            using (TripleDES tripleDes = TripleDES.Create())
            // Create a TripleDES encryptor from the key and IV
            using (ICryptoTransform encryptor = tripleDes.CreateEncryptor(key, iv))
            // Create a CryptoStream using the FileStream and encryptor
            using (var cStream = new CryptoStream(fStream, encryptor, CryptoStreamMode.Write))
            {
                // Convert the provided string to a byte array.
                byte[] toEncrypt = Encoding.UTF8.GetBytes(text);

                // Write the byte array to the crypto stream.
                cStream.Write(toEncrypt, 0, toEncrypt.Length);
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            throw;
        }
    }

    public static string DecryptTextFromFile(string path, byte[] key, byte[] iv)
    {
        try
        {
            // Open the specified file
            using (FileStream fStream = File.OpenRead(path))
            // Create a new TripleDES object.
            using (TripleDES tripleDes = TripleDES.Create())
            // Create a TripleDES decryptor from the key and IV
            using (ICryptoTransform decryptor = tripleDes.CreateDecryptor(key, iv))
            // Create a CryptoStream using the FileStream and decryptor
            using (var cStream = new CryptoStream(fStream, decryptor, CryptoStreamMode.Read))
            // Create a StreamReader to turn the bytes back into text
            using (StreamReader reader = new StreamReader(cStream, Encoding.UTF8))
            {
                // Read back all of the text from the StreamReader, which receives
                // the decrypted bytes from the CryptoStream, which receives the
                // encrypted bytes from the FileStream.
                return reader.ReadToEnd();
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            throw;
        }
    }
}
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text

Module TripleDESSample

    Sub Main()
        Try
            Dim key As Byte()
            Dim iv As Byte()

            ' Create a new TripleDES object to generate a key
            ' and initialization vector (IV).
            Using tripleDes As TripleDES = TripleDES.Create
                key = tripleDes.Key
                iv = tripleDes.IV
            End Using

            ' Create a string to encrypt.
            Dim original As String = "Here is some data to encrypt."
            ' The name/path of the file to write.
            Dim filename As String = "CText.enc"

            ' Encrypt the string to a file.
            EncryptTextToFile(original, filename, key, iv)

            ' Decrypt the file back to a string.
            Dim decrypted As String = DecryptTextFromFile(filename, key, iv)

            ' Display the decrypted string to the console.
            Console.WriteLine(decrypted)
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try
    End Sub


    Sub EncryptTextToFile(text As String, path As String, key As Byte(), iv As Byte())
        Try
            ' Create or open the specified file.
            ' Create a new TripleDES object,
            ' Create a TripleDES encryptor from the key and IV,
            ' Create a CryptoStream using the MemoryStream And encryptor
            Using fStream As FileStream = File.Open(path, FileMode.Create),
                tripleDes As TripleDES = TripleDES.Create,
                encryptor As ICryptoTransform = tripleDes.CreateEncryptor(key, iv),
                cStream = New CryptoStream(fStream, encryptor, CryptoStreamMode.Write)

                ' Convert the passed string to a byte array.
                Dim toEncrypt As Byte() = Encoding.UTF8.GetBytes(text)

                ' Write the byte array to the crypto stream.
                cStream.Write(toEncrypt, 0, toEncrypt.Length)
            End Using

        Catch e As CryptographicException
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
            Throw
        End Try
    End Sub


    Function DecryptTextFromFile(path As String, key As Byte(), iv As Byte()) As String
        Try
            ' Open the specified file
            ' Create a new TripleDES object.
            ' Create a TripleDES decryptor from the key and IV
            ' Create a CryptoStream using the MemoryStream and decryptor
            ' Create a StreamReader to turn the bytes back into text
            Using mStream As FileStream = File.OpenRead(path),
                tripleDes As TripleDES = TripleDES.Create,
                decryptor As ICryptoTransform = tripleDes.CreateDecryptor(key, iv),
                cStream = New CryptoStream(mStream, decryptor, CryptoStreamMode.Read),
                reader = New StreamReader(cStream, Encoding.UTF8)

                ' Read back all of the text from the StreamReader, which receives
                ' the decrypted bytes from the CryptoStream, which receives the
                ' encrypted bytes from the FileStream.
                Return reader.ReadToEnd()
            End Using
        Catch e As CryptographicException
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
            Return Nothing
        End Try
    End Function
End Module

다음 코드 예제를 만들고 사용 하는 방법에 설명 합니다 TripleDES 암호화 하 고 메모리에서 데이터를 암호 해독 하는 개체입니다.

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

array<Byte>^ EncryptTextToMemory(String^ text, array<Byte>^ key, array<Byte>^ iv);
String^ DecryptTextFromMemory(array<Byte>^ encrypted, array<Byte>^ key, array<Byte>^ iv);

int main()
{
    try
    {
        array<Byte>^ key;
        array<Byte>^ iv;

        // Create a new TripleDES object to generate a random key
        // and initialization vector (IV).
        {
            TripleDES^ tripleDes;

            try
            {
                tripleDes = TripleDES::Create();
                key = tripleDes->Key;
                iv = tripleDes->IV;
            }
            finally
            {
                delete tripleDes;
            }
        }

        // Create a string to encrypt.
        String^ original = "Here is some data to encrypt.";

        // Encrypt the string to an in-memory buffer.
        array<Byte>^ encrypted = EncryptTextToMemory(original, key, iv);

        // Decrypt the buffer back to a string.
        String^ decrypted = DecryptTextFromMemory(encrypted, key, iv);

        // Display the decrypted string to the console.
        Console::WriteLine(decrypted);
    }
    catch (Exception^ e)
    {
        Console::WriteLine(e->Message);
    }
}

array<Byte>^ EncryptTextToMemory(String^ text, array<Byte>^ key, array<Byte>^ iv)
{
    MemoryStream^ mStream = nullptr;

    try
    {
        // Create a MemoryStream.
        mStream = gcnew MemoryStream;

        TripleDES^ tripleDes = nullptr;
        ICryptoTransform^ encryptor = nullptr;
        CryptoStream^ cStream = nullptr;

        try
        {
            // Create a new TripleDES object.
            tripleDes = TripleDES::Create();
            // Create a TripleDES encryptor from the key and IV
            encryptor = tripleDes->CreateEncryptor(key, iv);
            // Create a CryptoStream using the MemoryStream and encryptor
            cStream = gcnew CryptoStream(mStream, encryptor, CryptoStreamMode::Write);

            // Convert the provided string to a byte array.
            array<Byte>^ toEncrypt = Encoding::UTF8->GetBytes(text);

            // Write the byte array to the crypto stream.
            cStream->Write(toEncrypt, 0, toEncrypt->Length);

            // Disposing the CryptoStream completes the encryption and flushes the stream.
            delete cStream;

            // Get an array of bytes from the MemoryStream that holds the encrypted data.
            array<Byte>^ ret = mStream->ToArray();

            // Return the encrypted buffer.
            return ret;
        }
        finally
        {
            if (cStream != nullptr)
                delete cStream;

            if (encryptor != nullptr)
                delete encryptor;

            if (tripleDes != nullptr)
                delete tripleDes;
        }
    }
    catch (CryptographicException^ e)
    {
        Console::WriteLine("A Cryptographic error occurred: {0}", e->Message);
        throw;
    }
    finally
    {
        if (mStream != nullptr)
            delete mStream;
    }
}

String^ DecryptTextFromMemory(array<Byte>^ encrypted, array<Byte>^ key, array<Byte>^ iv)
{
    MemoryStream^ mStream = nullptr;
    TripleDES^ tripleDes = nullptr;
    ICryptoTransform^ decryptor = nullptr;
    CryptoStream^ cStream = nullptr;

    try
    {
        // Create buffer to hold the decrypted data.
        // TripleDES-encrypted data will always be slightly bigger than the decrypted data.
        array<Byte>^ decrypted = gcnew array<Byte>(encrypted->Length);
        Int32 offset = 0;

        // Create a new MemoryStream using the provided array of encrypted data.
        mStream = gcnew MemoryStream(encrypted);
        // Create a new TripleDES object.
        tripleDes = TripleDES::Create();
        // Create a TripleDES decryptor from the key and IV
        decryptor = tripleDes->CreateDecryptor(key, iv);
        // Create a CryptoStream using the MemoryStream and decryptor
        cStream = gcnew CryptoStream(mStream, decryptor, CryptoStreamMode::Read);

        // Keep reading from the CryptoStream until it finishes (returns 0).
        Int32 read = 1;

        while (read > 0)
        {
            read = cStream->Read(decrypted, offset, decrypted->Length - offset);
            offset += read;
        }

        // Convert the buffer into a string and return it.
        return Encoding::UTF8->GetString(decrypted, 0, offset);
    }
    catch (CryptographicException^ e)
    {
        Console::WriteLine("A Cryptographic error occurred: {0}", e->Message);
        throw;
    }
    finally
    {
        if (cStream != nullptr)
            delete cStream;

        if (decryptor != nullptr)
            delete decryptor;

        if (tripleDes != nullptr)
            delete tripleDes;

        if (mStream != nullptr)
            delete mStream;
    }
}
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Module TripleDESSample

    Sub Main()
        Try
            Dim key As Byte()
            Dim iv As Byte()

            ' Create a new TripleDES object to generate a key
            ' and initialization vector (IV).
            Using tripleDes As TripleDES = TripleDES.Create
                key = tripleDes.Key
                iv = tripleDes.IV
            End Using

            ' Create a string to encrypt.
            Dim original As String = "Here is some data to encrypt."

            ' Encrypt the string to an in-memory buffer.
            Dim encrypted As Byte() = EncryptTextToMemory(original, key, iv)

            ' Decrypt the buffer back to a string.
            Dim decrypted As String = DecryptTextFromMemory(encrypted, key, iv)

            ' Display the decrypted string to the console.
            Console.WriteLine(decrypted)
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try
    End Sub


    Function EncryptTextToMemory(text As String, key As Byte(), iv As Byte()) As Byte()
        Try
            ' Create a MemoryStream.
            Using mStream As New MemoryStream
                ' Create a new TripleDES object,
                ' Create a TripleDES encryptor from the key and IV,
                ' Create a CryptoStream using the MemoryStream And encryptor
                Using tripleDes As TripleDES = TripleDES.Create,
                    encryptor As ICryptoTransform = tripleDes.CreateEncryptor(key, iv),
                    cStream = New CryptoStream(mStream, encryptor, CryptoStreamMode.Write)

                    ' Convert the passed string to a byte array.
                    Dim toEncrypt As Byte() = Encoding.UTF8.GetBytes(text)

                    ' Write the byte array to the crypto stream and flush it.
                    cStream.Write(toEncrypt, 0, toEncrypt.Length)

                    ' Ending the using block for the CryptoStream completes the encryption.
                End Using

                ' Get an array of bytes from the MemoryStream that holds the encrypted data.
                Dim ret As Byte() = mStream.ToArray()

                ' Return the encrypted buffer.
                Return ret
            End Using
        Catch e As CryptographicException
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
            Throw
        End Try
    End Function


    Function DecryptTextFromMemory(encrypted As Byte(), key As Byte(), iv As Byte()) As String
        Try
            ' Create a buffer to hold the decrypted data.
            ' TripleDES-encrypted data will always be slightly bigger than the decrypted data.
            Dim decrypted(encrypted.Length - 1) As Byte
            Dim offset As Integer = 0

            ' Create a new MemoryStream using the provided array of encrypted data.
            ' Create a new TripleDES object.
            ' Create a TripleDES decryptor from the key and IV
            ' Create a CryptoStream using the MemoryStream and decryptor
            Using mStream As New MemoryStream(encrypted),
                tripleDes As TripleDES = TripleDES.Create,
                decryptor As ICryptoTransform = tripleDes.CreateDecryptor(key, iv),
                cStream = New CryptoStream(mStream, decryptor, CryptoStreamMode.Read)

                ' Keep reading from the CryptoStream until it finishes (returns 0).
                Dim read As Integer = 1

                While (read > 0)
                    read = cStream.Read(decrypted, offset, decrypted.Length - offset)
                    offset += read
                End While
            End Using

            ' Convert the buffer into a string and return it.
            Return New ASCIIEncoding().GetString(decrypted, 0, offset)
        Catch e As CryptographicException
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
            Return Nothing
        End Try
    End Function
End Module

설명

TripleDES 클래스의 새 인스턴스를 만듭니다.

추가 정보

적용 대상

Create(String)

Source:
TripleDES.cs
Source:
TripleDES.cs
Source:
TripleDES.cs

주의

Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead.

암호화 개체의 인스턴스를 만들어 지정된 방식으로 TripleDES 알고리즘을 구현합니다.

public:
 static System::Security::Cryptography::TripleDES ^ Create(System::String ^ str);
public static System.Security.Cryptography.TripleDES? Create (string str);
[System.Obsolete("Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead.", DiagnosticId="SYSLIB0045", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public static System.Security.Cryptography.TripleDES? Create (string str);
public static System.Security.Cryptography.TripleDES Create (string str);
static member Create : string -> System.Security.Cryptography.TripleDES
[<System.Obsolete("Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead.", DiagnosticId="SYSLIB0045", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
static member Create : string -> System.Security.Cryptography.TripleDES
Public Shared Function Create (str As String) As TripleDES

매개 변수

str
String

사용하려는 TripleDES의 특정 구현에 대한 이름입니다.

반환

암호화 개체의 인스턴스입니다.

특성

추가 정보

적용 대상