Ler em inglês

Partilhar via


TripleDES.Create Método

Definição

Cria uma instância de um objeto criptográfico para executar o algoritmo TripleDES.

Sobrecargas

Create()

Cria uma instância de um objeto criptográfico para executar o algoritmo TripleDES.

Create(String)
Obsoleto.

Cria uma instância de um objeto criptográfico para realizar a implementação especificada do algoritmo TripleDES.

Create()

Origem:
TripleDES.cs
Origem:
TripleDES.cs
Origem:
TripleDES.cs

Cria uma instância de um objeto criptográfico para executar o algoritmo TripleDES.

C#
public static System.Security.Cryptography.TripleDES Create();
C#
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static System.Security.Cryptography.TripleDES Create();

Retornos

Uma instância de um objeto de criptografia.

Atributos

Exemplos

O exemplo de código a seguir mostra como criar e usar um TripleDES objeto para criptografar e descriptografar dados em um arquivo.

C#
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;
        }
    }
}

O exemplo de código a seguir mostra como criar e usar um TripleDES objeto para criptografar e descriptografar dados na memória.

C++
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;
    }
}

Comentários

Cria uma nova instância da classe TripleDES.

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1

Create(String)

Origem:
TripleDES.cs
Origem:
TripleDES.cs
Origem:
TripleDES.cs

Cuidado

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

Cria uma instância de um objeto criptográfico para realizar a implementação especificada do algoritmo TripleDES.

C#
public static System.Security.Cryptography.TripleDES? Create(string str);
C#
[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);
C#
public static System.Security.Cryptography.TripleDES Create(string str);

Parâmetros

str
String

O nome da implementação específica do TripleDES a ser usada.

Retornos

Uma instância de um objeto de criptografia.

Atributos

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões (Obsoleto)
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6 (7, 8, 9)
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1