Leer en inglés

Compartir a través de


RC2.Create Método

Definición

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

Sobrecargas

Create()

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

Create(String)
Obsoletos.

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

Create()

Source:
RC2.cs
Source:
RC2.cs
Source:
RC2.cs

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

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

Devoluciones

RC2

Una instancia de un objeto criptográfico.

Atributos

Excepciones

El algoritmo se usó con el modo FIPS (Estándar federal de procesamiento de información) habilitado, pero no es compatible con FIPS.

Ejemplos

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

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

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

            // Create a new RC2 object to generate a random key
            // and initialization vector (IV).
            using (RC2 rc2 = RC2.Create())
            {
                key = rc2.Key;
                iv = rc2.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 RC2 object.
            using (RC2 rc2 = RC2.Create())
            // Create an RC2 encryptor from the key and IV
            using (ICryptoTransform encryptor = rc2.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 RC2 object.
            using (RC2 rc2 = RC2.Create())
            // Create an RC2 decryptor from the key and IV
            using (ICryptoTransform decryptor = rc2.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;
        }
    }
}

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

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

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

            // Create a new RC2 object to generate a random key
            // and initialization vector (IV).
            using (RC2 rc2 = RC2.Create())
            {
                key = rc2.Key;
                iv = rc2.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 RC2 object.
                using (RC2 rc2 = RC2.Create())
                // Create an RC2 encryptor from the key and IV
                using (ICryptoTransform encryptor = rc2.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.
            // RC2-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 RC2 object.
                using (RC2 rc2 = RC2.Create())
                // Create an RC2 decryptor from the key and IV
                using (ICryptoTransform decryptor = rc2.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;
        }
    }
}

Comentarios

Use este método para crear una instancia de la clase RC2 que puede usar para cifrar y descifrar datos.

Consulte también

Se aplica a

.NET 9 y otras versiones
Producto Versiones
.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

Create(String)

Source:
RC2.cs
Source:
RC2.cs
Source:
RC2.cs

Precaución

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

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

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

Parámetros

AlgName
String

Nombre de la implementación específica de RC2 que se va a utilizar.

Devoluciones

RC2

Una instancia de un objeto criptográfico.

Atributos

Excepciones

Se utilizó el algoritmo descrito por el parámetro algName con el modo FIPS (Estándar federal de procesamiento de información) habilitado, pero no es compatible con FIPS.

Consulte también

Se aplica a

.NET 9 y otras versiones
Producto Versiones (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