TripleDES Clase

Definición

Representa la clase base para los algoritmos estándar de cifrado de datos triple de los que deben derivarse todas las TripleDES implementaciones.

public ref class TripleDES abstract : System::Security::Cryptography::SymmetricAlgorithm
public abstract class TripleDES : System.Security.Cryptography.SymmetricAlgorithm
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class TripleDES : System.Security.Cryptography.SymmetricAlgorithm
type TripleDES = class
    inherit SymmetricAlgorithm
[<System.Runtime.InteropServices.ComVisible(true)>]
type TripleDES = class
    inherit SymmetricAlgorithm
Public MustInherit Class TripleDES
Inherits SymmetricAlgorithm
Herencia
Derivado
Atributos

Ejemplos

En el ejemplo de código siguiente se muestra cómo crear y usar un TripleDES objeto para cifrar y descifrar datos en un archivo.

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

En el ejemplo de código siguiente se muestra cómo crear y usar un TripleDES objeto para cifrar y descifrar datos en memoria.

using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

class TripleDESSample2
{
    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.";

            // Encrypt the string to an in-memory buffer.
            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);
        }
    }

    public static byte[] EncryptTextToMemory(string text, byte[] key, byte[] iv)
    {
        try
        {
            // Create a MemoryStream.
            using (MemoryStream mStream = new MemoryStream())
            {
                // 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 MemoryStream and encryptor
                using (var cStream = new CryptoStream(mStream, 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 and flush it.
                    cStream.Write(toEncrypt, 0, toEncrypt.Length);

                    // Ending the using statement for the CryptoStream completes the encryption.
                }

                // Get an array of bytes from the MemoryStream that holds the encrypted data.
                byte[] ret = mStream.ToArray();

                // Return the encrypted buffer.
                return ret;
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            throw;
        }
    }

    public static string DecryptTextFromMemory(byte[] encrypted, byte[] key, byte[] iv)
    {
        try
        {
            // Create a buffer to hold the decrypted data.
            // TripleDES-encrypted data will always be slightly bigger than the decrypted data.
            byte[] decrypted = new byte[encrypted.Length];
            int offset = 0;

            // Create a new MemoryStream using the provided array of encrypted data.
            using (MemoryStream mStream = new MemoryStream(encrypted))
            {
                // 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 MemoryStream and decryptor
                using (var cStream = new CryptoStream(mStream, decryptor, CryptoStreamMode.Read))
                {
                    // Keep reading from the CryptoStream until it finishes (returns 0).
                    int 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;
        }
    }
}
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Module MemorySample

    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

Comentarios

TripleDES usa tres iteraciones sucesivas del DES algoritmo. Puede usar dos o tres claves de 56 bits.

Note

Hay disponible un algoritmo de cifrado simétrico más reciente, Advanced Encryption Standard (AES). Considere la posibilidad de usar la Aes clase y sus clases derivadas en lugar de la TripleDES clase . Use TripleDES solo para la compatibilidad con aplicaciones y datos heredados.

Este algoritmo admite longitudes de clave de 128 bits a 192 bits en incrementos de 64 bits.

Constructores

Nombre Description
TripleDES()

Inicializa una nueva instancia de la clase TripleDES.

Campos

Nombre Description
BlockSizeValue

Representa el tamaño del bloque, en bits, de la operación criptográfica.

(Heredado de SymmetricAlgorithm)
FeedbackSizeValue

Representa el tamaño de comentarios, en bits, de la operación criptográfica.

(Heredado de SymmetricAlgorithm)
IVValue

Representa el vector de inicialización (IV) para el algoritmo simétrico.

(Heredado de SymmetricAlgorithm)
KeySizeValue

Representa el tamaño, en bits, de la clave secreta utilizada por el algoritmo simétrico.

(Heredado de SymmetricAlgorithm)
KeyValue

Representa la clave secreta del algoritmo simétrico.

(Heredado de SymmetricAlgorithm)
LegalBlockSizesValue

Especifica los tamaños de bloque, en bits, que son compatibles con el algoritmo simétrico.

(Heredado de SymmetricAlgorithm)
LegalKeySizesValue

Especifica los tamaños de clave, en bits, que son compatibles con el algoritmo simétrico.

(Heredado de SymmetricAlgorithm)
ModeValue

Representa el modo de cifrado utilizado en el algoritmo simétrico.

(Heredado de SymmetricAlgorithm)
PaddingValue

Representa el modo de relleno utilizado en el algoritmo simétrico.

(Heredado de SymmetricAlgorithm)

Propiedades

Nombre Description
BlockSize

Obtiene o establece el tamaño de bloque, en bits, de la operación criptográfica.

(Heredado de SymmetricAlgorithm)
FeedbackSize

Obtiene o establece el tamaño de comentarios, en bits, de la operación criptográfica para los modos de cifrado Comentarios de cifrado (CFB) y Comentarios de salida (OFB).

(Heredado de SymmetricAlgorithm)
IV

Obtiene o establece el vector de inicialización (IV) para el algoritmo simétrico.

(Heredado de SymmetricAlgorithm)
Key

Obtiene o establece la clave secreta para el TripleDES algoritmo.

KeySize

Obtiene o establece el tamaño, en bits, de la clave secreta utilizada por el algoritmo simétrico.

(Heredado de SymmetricAlgorithm)
LegalBlockSizes

Obtiene los tamaños de bloque, en bits, que son compatibles con el algoritmo simétrico.

LegalBlockSizes

Obtiene los tamaños de bloque, en bits, que son compatibles con el algoritmo simétrico.

(Heredado de SymmetricAlgorithm)
LegalKeySizes

Obtiene los tamaños de clave, en bits, que son compatibles con el algoritmo simétrico.

LegalKeySizes

Obtiene los tamaños de clave, en bits, que son compatibles con el algoritmo simétrico.

(Heredado de SymmetricAlgorithm)
Mode

Obtiene o establece el modo para el funcionamiento del algoritmo simétrico.

(Heredado de SymmetricAlgorithm)
Padding

Obtiene o establece el modo de relleno utilizado en el algoritmo simétrico.

(Heredado de SymmetricAlgorithm)

Métodos

Nombre Description
Clear()

Libera todos los recursos usados por la SymmetricAlgorithm clase .

(Heredado de SymmetricAlgorithm)
Create()

Crea una instancia de un objeto criptográfico para realizar el TripleDES algoritmo.

Create(String)

Crea una instancia de un objeto criptográfico para realizar la implementación especificada del TripleDES algoritmo.

CreateDecryptor()

Crea un objeto de descifrador simétrico con la propiedad actual Key y el vector de inicialización (IV).

(Heredado de SymmetricAlgorithm)
CreateDecryptor(Byte[], Byte[])

Cuando se reemplaza en una clase derivada, crea un objeto de descifrador simétrico con la propiedad y el vector de inicialización especificados Key (IV).

(Heredado de SymmetricAlgorithm)
CreateEncryptor()

Crea un objeto encryptor simétrico con la propiedad actual Key y el vector de inicialización (IV).

(Heredado de SymmetricAlgorithm)
CreateEncryptor(Byte[], Byte[])

Cuando se reemplaza en una clase derivada, crea un objeto encryptor simétrico con la propiedad y el vector de inicialización especificados Key (IV).

(Heredado de SymmetricAlgorithm)
Dispose()

Libera todos los recursos usados por la instancia actual de la SymmetricAlgorithm clase .

(Heredado de SymmetricAlgorithm)
Dispose(Boolean)

Libera los recursos no administrados utilizados por SymmetricAlgorithm y, opcionalmente, libera los recursos administrados.

(Heredado de SymmetricAlgorithm)
Equals(Object)

Determina si el objeto especificado es igual al objeto actual.

(Heredado de Object)
GenerateIV()

Cuando se reemplaza en una clase derivada, genera un vector de inicialización aleatorio (IV) que se usará para el algoritmo.

(Heredado de SymmetricAlgorithm)
GenerateKey()

Cuando se invalida en una clase derivada, genera una clave aleatoria (Key) que se usará para el algoritmo.

(Heredado de SymmetricAlgorithm)
GetHashCode()

Actúa como la función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
IsWeakKey(Byte[])

Determina si la clave especificada es débil.

MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)
ValidKeySize(Int32)

Determina si el tamaño de clave especificado es válido para el algoritmo actual.

(Heredado de SymmetricAlgorithm)

Implementaciones de interfaz explícitas

Nombre Description
IDisposable.Dispose()

Esta API admite la infraestructura de producto y no está pensada para usarse directamente en el código.

Libera los recursos no administrados utilizados por SymmetricAlgorithm y, opcionalmente, libera los recursos administrados.

(Heredado de SymmetricAlgorithm)

Se aplica a

Consulte también