RC2.Create Método

Definição

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

Sobrecargas

Create()

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

Create(String)

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

Create()

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

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

Retornos

RC2

Uma instância de um objeto de criptografia.

Atributos

Exceções

O algoritmo foi usado com o modo FIPS (Federal Information Processing Standards) habilitado, mas ele não é compatível com FIPS.

Exemplos

O exemplo a seguir mostra como criar e usar um objeto RC2 para criptografar e descriptografar dados em um arquivo.

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 RC2 object to generate a random key
        // and initialization vector (IV).
        {
            RC2^ rc2;

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

        // 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;
    RC2^ rc2 = nullptr;
    ICryptoTransform^ encryptor = nullptr;
    CryptoStream^ cStream = nullptr;

    try
    {
        // Create or open the specified file.
        fStream = File::Open(path, FileMode::Create);
        // Create a new RC2 object.
        rc2 = RC2::Create();
        // Create an RC2 encryptor from the key and IV
        encryptor = rc2->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 (rc2 != nullptr)
            delete rc2;

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

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

    try
    {
        // Open the specified file
        fStream = File::OpenRead(path);
        // Create a new RC2 object.
        rc2 = RC2::Create();
        // Create an RC2 decryptor from the key and IV
        decryptor = rc2->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 (rc2 != nullptr)
            delete rc2;

        if (fStream != nullptr)
            delete fStream;
    }
}
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;
        }
    }
}
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text

Module RC2Sample

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

            ' Create a new RC2 object to generate a key
            ' and initialization vector (IV).
            Using rc2 As RC2 = RC2.Create
                key = rc2.Key
                iv = rc2.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 RC2 object,
            ' Create an RC2 encryptor from the key and IV,
            ' Create a CryptoStream using the MemoryStream And encryptor
            Using fStream As FileStream = File.Open(path, FileMode.Create),
                rc2 As RC2 = RC2.Create,
                encryptor As ICryptoTransform = rc2.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 RC2 object.
            ' Create an RC2 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),
                rc2 As RC2 = RC2.Create,
                decryptor As ICryptoTransform = rc2.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

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

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 RC2 object to generate a random key
        // and initialization vector (IV).
        {
            RC2^ rc2;

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

        // 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;

        RC2^ rc2 = nullptr;
        ICryptoTransform^ encryptor = nullptr;
        CryptoStream^ cStream = nullptr;

        try
        {
            // Create a new RC2 object.
            rc2 = RC2::Create();
            // Create an RC2 encryptor from the key and IV
            encryptor = rc2->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 (rc2 != nullptr)
                delete rc2;
        }
    }
    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;
    RC2^ rc2 = nullptr;
    ICryptoTransform^ decryptor = nullptr;
    CryptoStream^ cStream = nullptr;

    try
    {
        // Create buffer to hold the decrypted data.
        // RC2-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 RC2 object.
        rc2 = RC2::Create();
        // Create an RC2 decryptor from the key and IV
        decryptor = rc2->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 (rc2 != nullptr)
            delete rc2;

        if (mStream != nullptr)
            delete mStream;
    }
}
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;
        }
    }
}
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Module RC2Sample

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

            ' Create a new RC2 object to generate a key
            ' and initialization vector (IV).
            Using rc2 As RC2 = RC2.Create
                key = rc2.Key
                iv = rc2.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 RC2 object,
                ' Create an RC2 encryptor from the key and IV,
                ' Create a CryptoStream using the MemoryStream And encryptor
                Using rc2 As RC2 = RC2.Create,
                    encryptor As ICryptoTransform = rc2.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.
            ' RC2-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 RC2 object.
            ' Create an RC2 decryptor from the key and IV
            ' Create a CryptoStream using the MemoryStream and decryptor
            Using mStream As New MemoryStream(encrypted),
                rc2 As RC2 = RC2.Create,
                decryptor As ICryptoTransform = rc2.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

Comentários

Use esse método para criar uma instância da classe RC2 que você pode usar para criptografar e descriptografar dados.

Confira também

Aplica-se a

Create(String)

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

public:
 static System::Security::Cryptography::RC2 ^ Create(System::String ^ AlgName);
public static System.Security.Cryptography.RC2? Create (string AlgName);
public static System.Security.Cryptography.RC2 Create (string AlgName);
static member Create : string -> System.Security.Cryptography.RC2
Public Shared Function Create (AlgName As String) As RC2

Parâmetros

AlgName
String

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

Retornos

RC2

Uma instância de um objeto de criptografia.

Exceções

O algoritmo descrito pelo parâmetro algName foi usado com o modo FIPS (Federal Information Processing Standards) habilitado, mas ele não é compatível com FIPS.

Exemplos

O exemplo a seguir mostra como criar e usar um objeto RC2 para criptografar e descriptografar dados em um arquivo.

using namespace System;
using namespace System::Security::Cryptography;
using namespace System::Text;
using namespace System::IO;
void EncryptTextToFile( String^ Data, String^ FileName, array<Byte>^Key, array<Byte>^IV )
{
   try
   {
      
      // Create or open the specified file.
      FileStream^ fStream = File::Open( FileName, FileMode::OpenOrCreate );
      
      // Create a new RC2 object.
      RC2^ RC2alg = RC2::Create();
      
      // Create a CryptoStream using the FileStream 
      // and the passed key and initialization vector (IV).
      CryptoStream^ cStream = gcnew CryptoStream( fStream,RC2alg->CreateEncryptor( Key, IV ),CryptoStreamMode::Write );
      
      // Create a StreamWriter using the CryptoStream.
      StreamWriter^ sWriter = gcnew StreamWriter( cStream );
      
      // Write the data to the stream 
      // to encrypt it.
      sWriter->WriteLine( Data );
      
      // Close the streams and
      // close the file.
      sWriter->Close();
      cStream->Close();
      fStream->Close();
   }
   catch ( CryptographicException^ e ) 
   {
      Console::WriteLine( "A Cryptographic error occurred: {0}", e->Message );
   }
   catch ( UnauthorizedAccessException^ e ) 
   {
      Console::WriteLine( "A file error occurred: {0}", e->Message );
   }

}

String^ DecryptTextFromFile( String^ FileName, array<Byte>^Key, array<Byte>^IV )
{
   try
   {
      
      // Create or open the specified file. 
      FileStream^ fStream = File::Open( FileName, FileMode::OpenOrCreate );
      
      // Create a new RC2 object.
      RC2^ RC2alg = RC2::Create();
      
      // Create a CryptoStream using the FileStream 
      // and the passed key and initialization vector (IV).
      CryptoStream^ cStream = gcnew CryptoStream( fStream,RC2alg->CreateDecryptor( Key, IV ),CryptoStreamMode::Read );
      
      // Create a StreamReader using the CryptoStream.
      StreamReader^ sReader = gcnew StreamReader( cStream );
      
      // Read the data from the stream 
      // to decrypt it.
      String^ val = sReader->ReadLine();
      
      // Close the streams and
      // close the file.
      sReader->Close();
      cStream->Close();
      fStream->Close();
      
      // Return the string. 
      return val;
   }
   catch ( CryptographicException^ e ) 
   {
      Console::WriteLine( "A Cryptographic error occurred: {0}", e->Message );
      return nullptr;
   }
   catch ( UnauthorizedAccessException^ e ) 
   {
      Console::WriteLine( "A file error occurred: {0}", e->Message );
      return nullptr;
   }

}

int main()
{
   try
   {
      
      // Create a new RC2 object to generate a key 
      // and initialization vector (IV).  Specify one 
      // of the recognized simple names for this 
      // algorithm.
      RC2^ RC2alg = RC2::Create( "RC2" );
      
      // Create a string to encrypt.
      String^ sData = "Here is some data to encrypt.";
      String^ FileName = "CText.txt";
      
      // Encrypt text to a file using the file name, key, and IV.
      EncryptTextToFile( sData, FileName, RC2alg->Key, RC2alg->IV );
      
      // Decrypt the text from a file using the file name, key, and IV.
      String^ Final = DecryptTextFromFile( FileName, RC2alg->Key, RC2alg->IV );
      
      // Display the decrypted string to the console.
      Console::WriteLine( Final );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( e->Message );
   }

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

class RC2Sample
{

    static void Main()
    {
        try
        {
            // Create a new RC2 object to generate a key
            // and initialization vector (IV).  Specify one
            // of the recognized simple names for this
            // algorithm.
            RC2 RC2alg = RC2.Create("RC2");

            // Create a string to encrypt.
            string sData = "Here is some data to encrypt.";
            string FileName = "CText.txt";

            // Encrypt text to a file using the file name, key, and IV.
            EncryptTextToFile(sData, FileName, RC2alg.Key, RC2alg.IV);

            // Decrypt the text from a file using the file name, key, and IV.
            string Final = DecryptTextFromFile(FileName, RC2alg.Key, RC2alg.IV);

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

    public static void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV)
    {
        try
        {
            // Create or open the specified file.
            FileStream fStream = File.Open(FileName,FileMode.OpenOrCreate);

            // Create a new RC2 object.
            RC2 RC2alg = RC2.Create();

            // Create a CryptoStream using the FileStream
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream(fStream,
                RC2alg.CreateEncryptor(Key,IV),
                CryptoStreamMode.Write);

            // Create a StreamWriter using the CryptoStream.
            StreamWriter sWriter = new StreamWriter(cStream);

            // Write the data to the stream
            // to encrypt it.
            sWriter.WriteLine(Data);

            // Close the streams and
            // close the file.
            sWriter.Close();
            cStream.Close();
            fStream.Close();
        }
        catch(CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
        }
        catch(UnauthorizedAccessException  e)
        {
            Console.WriteLine("A file error occurred: {0}", e.Message);
        }
    }

    public static string DecryptTextFromFile(String FileName, byte[] Key, byte[] IV)
    {
        try
        {
            // Create or open the specified file.
            FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);

            // Create a new RC2 object.
            RC2 RC2alg = RC2.Create();

            // Create a CryptoStream using the FileStream
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream(fStream,
                RC2alg.CreateDecryptor(Key,IV),
                CryptoStreamMode.Read);

            // Create a StreamReader using the CryptoStream.
            StreamReader sReader = new StreamReader(cStream);

            // Read the data from the stream
            // to decrypt it.
            string val = sReader.ReadLine();

            // Close the streams and
            // close the file.
            sReader.Close();
            cStream.Close();
            fStream.Close();

            // Return the string.
            return val;
        }
        catch(CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
        catch(UnauthorizedAccessException  e)
        {
            Console.WriteLine("A file error occurred: {0}", e.Message);
            return null;
        }
    }
}
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Module RC2Sample

    Sub Main()
        Try
            ' Create a new RC2 object to generate a key 
            ' and initialization vector (IV).  Specify one 
            ' of the recognized simple names for this 
            ' algorithm.
            Dim RC2alg As RC2 = RC2.Create("RC2")

            ' Create a string to encrypt.
            Dim sData As String = "Here is some data to encrypt."
            Dim FileName As String = "CText.txt"

            ' Encrypt text to a file using the file name, key, and IV.
            EncryptTextToFile(sData, FileName, RC2alg.Key, RC2alg.IV)

            ' Decrypt the text from a file using the file name, key, and IV.
            Dim Final As String = DecryptTextFromFile(FileName, RC2alg.Key, RC2alg.IV)

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


    Sub EncryptTextToFile(ByVal Data As String, ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte)
        Try
            ' Create or open the specified file.
            Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)

            ' Create a new RC2 object.
            Dim RC2alg As RC2 = RC2.Create

            ' Create a CryptoStream using the FileStream 
            ' and the passed key and initialization vector (IV).
            Dim cStream As New CryptoStream(fStream, _
                                           RC2alg.CreateEncryptor(Key, IV), _
                                           CryptoStreamMode.Write)

            ' Create a StreamWriter using the CryptoStream.
            Dim sWriter As New StreamWriter(cStream)

            ' Write the data to the stream 
            ' to encrypt it.
            sWriter.WriteLine(Data)

            ' Close the streams and
            ' close the file.
            sWriter.Close()
            cStream.Close()
            fStream.Close()
        Catch e As CryptographicException
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
        Catch e As UnauthorizedAccessException
            Console.WriteLine("A file error occurred: {0}", e.Message)
        End Try
    End Sub


    Function DecryptTextFromFile(ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte) As String
        Try
            ' Create or open the specified file. 
            Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)

            ' Create a new RC2 object.
            Dim RC2alg As RC2 = RC2.Create

            ' Create a CryptoStream using the FileStream 
            ' and the passed key and initialization vector (IV).
            Dim cStream As New CryptoStream(fStream, _
                                            RC2alg.CreateDecryptor(Key, IV), _
                                            CryptoStreamMode.Read)

            ' Create a StreamReader using the CryptoStream.
            Dim sReader As New StreamReader(cStream)

            ' Read the data from the stream 
            ' to decrypt it.
            Dim val As String = sReader.ReadLine()

            ' Close the streams and
            ' close the file.
            sReader.Close()
            cStream.Close()
            fStream.Close()

            ' Return the string. 
            Return val
        Catch e As CryptographicException
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
            Return Nothing
        Catch e As UnauthorizedAccessException
            Console.WriteLine("A file error occurred: {0}", e.Message)
            Return Nothing
        End Try
    End Function
End Module

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

using namespace System;
using namespace System::Security::Cryptography;
using namespace System::Text;
using namespace System::IO;
array<Byte>^ EncryptTextToMemory( String^ Data, array<Byte>^Key, array<Byte>^IV )
{
   try
   {
      
      // Create a MemoryStream.
      MemoryStream^ mStream = gcnew MemoryStream;
      
      // Create a new RC2 object.
      RC2^ RC2alg = RC2::Create();
      
      // Create a CryptoStream using the MemoryStream 
      // and the passed key and initialization vector (IV).
      CryptoStream^ cStream = gcnew CryptoStream( mStream,RC2alg->CreateEncryptor( Key, IV ),CryptoStreamMode::Write );
      
      // Convert the passed string to a byte array.
      array<Byte>^toEncrypt = (gcnew ASCIIEncoding)->GetBytes( Data );
      
      // Write the byte array to the crypto stream and flush it.
      cStream->Write( toEncrypt, 0, toEncrypt->Length );
      cStream->FlushFinalBlock();
      
      // Get an array of bytes from the 
      // MemoryStream that holds the 
      // encrypted data.
      array<Byte>^ret = mStream->ToArray();
      
      // Close the streams.
      cStream->Close();
      mStream->Close();
      
      // Return the encrypted buffer.
      return ret;
   }
   catch ( CryptographicException^ e ) 
   {
      Console::WriteLine( "A Cryptographic error occurred: {0}", e->Message );
      return nullptr;
   }

}

String^ DecryptTextFromMemory( array<Byte>^Data, array<Byte>^Key, array<Byte>^IV )
{
   try
   {
      
      // Create a new MemoryStream using the passed 
      // array of encrypted data.
      MemoryStream^ msDecrypt = gcnew MemoryStream( Data );
      
      // Create a new RC2 object.
      RC2^ RC2alg = RC2::Create();
      
      // Create a CryptoStream using the MemoryStream 
      // and the passed key and initialization vector (IV).
      CryptoStream^ csDecrypt = gcnew CryptoStream( msDecrypt,RC2alg->CreateDecryptor( Key, IV ),CryptoStreamMode::Read );
      
      // Create buffer to hold the decrypted data.
      array<Byte>^fromEncrypt = gcnew array<Byte>(Data->Length);
      
      // Read the decrypted data out of the crypto stream
      // and place it into the temporary buffer.
      csDecrypt->Read( fromEncrypt, 0, fromEncrypt->Length );
      
      //Convert the buffer into a string and return it.
      return (gcnew ASCIIEncoding)->GetString( fromEncrypt );
   }
   catch ( CryptographicException^ e ) 
   {
      Console::WriteLine( "A Cryptographic error occurred: {0}", e->Message );
      return nullptr;
   }

}

int main()
{
   try
   {
      
      // Create a new RC2 object to generate a key 
      // and initialization vector (IV).  Specify one 
      // of the recognized simple names for this 
      // algorithm.
      RC2^ RC2alg = RC2::Create( "RC2" );
      
      // Create a string to encrypt.
      String^ sData = "Here is some data to encrypt.";
      
      // Encrypt the string to an in-memory buffer.
      array<Byte>^Data = EncryptTextToMemory( sData, RC2alg->Key, RC2alg->IV );
      
      // Decrypt the buffer back to a string.
      String^ Final = DecryptTextFromMemory( Data, RC2alg->Key, RC2alg->IV );
      
      // Display the decrypted string to the console.
      Console::WriteLine( Final );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( e->Message );
   }

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

class RC2Sample
{
    static void Main()
    {
        try
        {
            // Create a new RC2 object to generate a key
            // and initialization vector (IV).  Specify one
            // of the recognized simple names for this
            // algorithm.
            RC2 RC2alg = RC2.Create("RC2");

            // Create a string to encrypt.
            string sData = "Here is some data to encrypt.";

            // Encrypt the string to an in-memory buffer.
            byte[] Data = EncryptTextToMemory(sData, RC2alg.Key, RC2alg.IV);

            // Decrypt the buffer back to a string.
            string Final = DecryptTextFromMemory(Data, RC2alg.Key, RC2alg.IV);

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

    public static byte[] EncryptTextToMemory(string Data,  byte[] Key, byte[] IV)
    {
        try
        {
            // Create a MemoryStream.
            MemoryStream mStream = new MemoryStream();

            // Create a new RC2 object.
            RC2 RC2alg = RC2.Create();

            // Create a CryptoStream using the MemoryStream
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream(mStream,
                RC2alg.CreateEncryptor(Key, IV),
                CryptoStreamMode.Write);

            // Convert the passed string to a byte array.
            byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);

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

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

            // Close the streams.
            cStream.Close();
            mStream.Close();

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

    public static string DecryptTextFromMemory(byte[] Data,  byte[] Key, byte[] IV)
    {
        try
        {
            // Create a new MemoryStream using the passed
            // array of encrypted data.
            MemoryStream msDecrypt = new MemoryStream(Data);

            // Create a new RC2 object.
            RC2 RC2alg = RC2.Create();

            // Create a CryptoStream using the MemoryStream
            // and the passed key and initialization vector (IV).
            CryptoStream csDecrypt = new CryptoStream(msDecrypt,
                RC2alg.CreateDecryptor(Key, IV),
                CryptoStreamMode.Read);

            // Create buffer to hold the decrypted data.
            byte[] fromEncrypt = new byte[Data.Length];

            // Read the decrypted data out of the crypto stream
            // and place it into the temporary buffer.
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

            //Convert the buffer into a string and return it.
            return new ASCIIEncoding().GetString(fromEncrypt);
        }
        catch(CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
    }
}
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Module RC2PSample

    Sub Main()
        Try
            ' Create a new RC2 object to generate a key 
            ' and initialization vector (IV).  Specify one 
            ' of the recognized simple names for this 
            ' algorithm.
            Dim RC2alg As RC2 = RC2.Create("RC2")

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

            ' Encrypt the string to an in-memory buffer.
            Dim Data As Byte() = EncryptTextToMemory(sData, RC2alg.Key, RC2alg.IV)

            ' Decrypt the buffer back to a string.
            Dim Final As String = DecryptTextFromMemory(Data, RC2alg.Key, RC2alg.IV)

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


    Function EncryptTextToMemory(ByVal Data As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte()
        Try
            ' Create a MemoryStream.
            Dim mStream As New MemoryStream

            ' Create a new RC2 object.
            Dim RC2alg As RC2 = RC2.Create

            ' Create a CryptoStream using the MemoryStream 
            ' and the passed key and initialization vector (IV).
            Dim cStream As New CryptoStream(mStream, _
                                            RC2alg.CreateEncryptor(Key, IV), _
                                            CryptoStreamMode.Write)

            ' Convert the passed string to a byte array.
            Dim toEncrypt As Byte() = New ASCIIEncoding().GetBytes(Data)

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

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

            ' Close the streams.
            cStream.Close()
            mStream.Close()

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


    Function DecryptTextFromMemory(ByVal Data() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String
        Try
            ' Create a new MemoryStream using the passed 
            ' array of encrypted data.
            Dim msDecrypt As New MemoryStream(Data)

            ' Create a new RC2 object.
            Dim RC2alg As RC2 = RC2.Create

            ' Create a CryptoStream using the MemoryStream 
            ' and the passed key and initialization vector (IV).
            Dim csDecrypt As New CryptoStream(msDecrypt, _
                                              RC2alg.CreateDecryptor(Key, IV), _
                                              CryptoStreamMode.Read)

            ' Create buffer to hold the decrypted data.
            Dim fromEncrypt(Data.Length - 1) As Byte

            ' Read the decrypted data out of the crypto stream
            ' and place it into the temporary buffer.
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length)

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

Comentários

Use esse método para criar uma instância da classe RC2 que você pode usar para criptografar e descriptografar dados.

Confira também

Aplica-se a