Compartilhar via


Demonstra Passo a passo: Criando um aplicativo de criptografia

Esta explicação passo a passo demonstra como criptografar e descriptografar o conteúdo.Os exemplos de código são projetados para um aplicativo Windows Forms.Este aplicativo não demonstram cenários do mundo real, tais sistema autônomo usando cartões inteligentes.Em vez disso, ele demonstra os conceitos básicos da criptografia e descriptografia.

Esta explicação passo a passo usa as seguintes diretrizes para a criptografia:

  • Use o RijndaelManaged classe, um algoritmo simétrico para criptografar e descriptografar dados usando gerado automaticamente Key e IV.

  • Use o RSACryptoServiceProvider, um algoritmo assimétrico, para criptografar e descriptografar a chave para os dados criptografados pela RijndaelManaged. Algoritmos assimétrica são melhor utilizados para quantidades menores de dados, sistema autônomo uma chave.

    Observação:

    Se você deseja para proteger dados em seu computador em vez de trocar conteúdo criptografado com outras pessoas , considere a possibilidade de usar o ProtectedData ou ProtectedMemory classes.

A tabela a seguir resume as tarefas de criptografia neste tópico.

Tarefa

Descrição

Criar um aplicativo Windows Forms

Lista os controles necessários para executar o aplicativo.

Declarar objetos global

Declara as variáveis de caminho, o seqüência de caracteresCspParameterse o RSACryptoServiceProvider para que o contexto global das Form classe.

Criar uma chave assimétrica

Cria um emparelhar de valor de chave pública e privada assimétrica e atribui a ele um nome de contêiner de chave.

Criptografia de um arquivo

Exibe uma caixa de diálogo para selecionar um arquivo para a criptografia e criptografa o arquivo.

Descriptografar um arquivo

Exibe uma caixa de diálogo para selecionar um arquivo criptografado para descriptografar e descriptografa o arquivo.

Obtendo uma chave particular

Obtém o emparelhar de chaves completo usando o nome de contêiner de chave.

Exportando uma chave pública

Salva a chave para um arquivo XML com somente parâmetros públicos.

Importar uma chave pública

Carrega a chave de um arquivo XML no contêiner de chave.

Teste do aplicativo

Lista os procedimentos para testar esse aplicativo.

Pré-requisitos

Para completar este passo a passo, são necessários os seguintes componentes:

Criando um aplicativo de formulários do Windows

A maioria dos exemplos de código nesta explicação passo a passo é projetada para serem manipuladores de eventos para controles de botão.A tabela a seguir lista os controles necessários para o aplicativo de exemplo e seus nomes necessárias coincidir com os exemplos de código.

Controle

Nome

Propriedade Texto (conforme o necessário)

Button

buttonEncryptFile

Criptografar arquivo

Button

buttonDecryptFile

Descriptografar arquivos

Button

buttonCreateAsmKeys

Criar chaves

Button

buttonExportPublicKey

Exportar a chave pública

Button

buttonImportPublicKey

Importação da chave pública

Button

buttonGetPrivateKey

Obtenha a chave particular

Label

label1

OpenFileDialog

openFileDialog1

OpenFileDialog

openFileDialog2

clicar duas vezes nos botões no designer do Visual Studio para criar seus evento manipuladores.

Declarar objetos global

Adicione o seguinte código ao construtor do formulário.Edite as variáveis de seqüência de caracteres para seu ambiente e preferências.

' Declare CspParmeters and RsaCryptoServiceProvider 
' objects with global scope of your Form class.
Dim cspp As CspParameters = New System.Security.Cryptography.CspParameters
Dim rsa As RSACryptoServiceProvider

' Path variables for source, encryption, and
' decryption folders. Must end with a backslash.
Dim EncrFolder As String = "c:\Encrypt\"
Dim DecrFolder As String = "c:\Decrypt\"
Dim SrcFolder As String = "c:\docs\"

' Public key file
Dim PubKeyFile As String = "c:\encrypt\rsaPublicKey.txt"

' Key container name for
' private/public key value pair.
Dim keyName As String = "Key01"
// Declare CspParmeters and RsaCryptoServiceProvider
// objects with global scope of your Form class.
CspParameters cspp = new CspParameters();
RSACryptoServiceProvider rsa;

// Path variables for source, encryption, and
// decryption folders. Must end with a backslash.
const string EncrFolder = @"c:\Encrypt\";
const string DecrFolder = @"c:\Decrypt\";
const string SrcFolder = @"c:\docs\";

// Public key file
const string PubKeyFile = @"c:\encrypt\rsaPublicKey.txt";

// Key container name for
// private/public key value pair.
const string keyName = "Key01";

Criar uma chave assimétrica

Esta tarefa cria uma chave assimétrica que criptografa e descriptografa o RijndaelManaged chave. Essa chave foi usada para criptografar o conteúdo e exibe o nome do contêiner de chave no controle de rótulo.

Adicione o código a seguir sistema autônomo a Click manipulador de eventos para o Create Keys botão (buttonCreateAsmKeys_Click).

Private Sub buttonCreateAsmKeys_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonCreateAsmKeys.Click
    ' Stores a key pair in the key container.
    cspp.KeyContainerName = keyName
    rsa = New RSACryptoServiceProvider(cspp)
    rsa.PersistKeyInCsp = True

    If rsa.PublicOnly = True Then
        Label1.Text = "Key: " + cspp.KeyContainerName + " - Public Only"
    Else
        Label1.Text = "Key: " + cspp.KeyContainerName + " - Full Key Pair"
    End If

End Sub
private void buttonCreateAsmKeys_Click(object sender, System.EventArgs e)
{
    // Stores a key pair in the key container.
    cspp.KeyContainerName = keyName;
    rsa = new RSACryptoServiceProvider(cspp);
    rsa.PersistKeyInCsp = true;
    if (rsa.PublicOnly == true)
       label1.Text = "Key: " + cspp.KeyContainerName + " - Public Only";
    else
       label1.Text = "Key: " + cspp.KeyContainerName + " - Full Key Pair";

}

Criptografar um arquivo

Essa tarefa envolve dois métodos: the event handler method for the Encrypt Filebutton (buttonEncryptFile_Click) and the EncryptFile method.O primeiro método exibe uma caixa de diálogo para selecionar um arquivo e passa nome de arquivo para o segundo método, que executa a criptografia.

O conteúdo criptografado, chave e IV são todos salvos para um FileStream, que é conhecido sistema autônomo o pacote de criptografia.

The EncryptFile método faz o seguinte:

  1. Cria um RijndaelManaged algoritmo simétrico para criptografar o conteúdo.

  2. Cria um RSACryptoServiceProvider objeto para criptografar o RijndaelManaged chave.

  3. Usa um CryptoStream objeto para ler e criptografar o FileStream do arquivo de fonte em blocos de bytes em um destino FileStream objeto para o arquivo criptografado.

  4. Determina o comprimento da chave criptografada e IV e cria matrizes de byte de seus valores de comprimento.

  5. Grava a chave, IV e seus valores de comprimento de pacote criptografado.

O pacote de criptografia usa o seguinte formato:

  • Comprimento da chave, bytes 0 - 3

  • Comprimento de IV, 4 a 7 bytes

  • Chave criptografada

  • IV

  • Texto codificado

Você pode usar os comprimentos de chave e IV para determinar os pontos inicial e comprimentos de todas as partes do pacote de criptografia, que pode ser usado para descriptografar o arquivo.

Adicione o código a seguir sistema autônomo a Click manipulador de eventos para o Encrypt File botão (buttonEncryptFile_Click).

Private Sub buttonEncryptFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonEncryptFile.Click
    If rsa Is Nothing Then
        MsgBox("Key not set.")
    Else
        ' Display a dialog box to select a file to encrypt.
        OpenFileDialog1.InitialDirectory = SrcFolder
        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Try
                Dim fName As String = OpenFileDialog1.FileName
                If (Not (fName) Is Nothing) Then
                    Dim fInfo As FileInfo = New FileInfo(fName)
                    ' Use just the file name without path.
                    Dim name As String = fInfo.Name
                    EncryptFile(name)
                End If
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If
    End If
End Sub
private void buttonEncryptFile_Click(object sender, System.EventArgs e)
{
    if (rsa == null)
        MessageBox.Show("Key not set.");
    else
    {

        // Display a dialog box to select a file to encrypt.
        openFileDialog1.InitialDirectory = SrcFolder;
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string fName = openFileDialog1.FileName;
            if (fName != null)
            {
                FileInfo fInfo = new FileInfo(fName);
                // Pass the file name without the path.
                string name = fInfo.Name;
                EncryptFile(name);
            }
        }
    }
}

Adicione o seguinte EncryptFile método para o formulário.

Private Sub EncryptFile(ByVal inFile As String)

    ' Create instance of Rijndael for
    ' symetric encryption of the data.
    Dim rjndl As RijndaelManaged = New RijndaelManaged
    rjndl.KeySize = 256
    rjndl.BlockSize = 256
    rjndl.Mode = CipherMode.CBC
    Dim transform As ICryptoTransform = rjndl.CreateEncryptor

    ' Use RSACryptoServiceProvider to 
    ' enrypt the Rijndael key.
    Dim keyEncrypted() As Byte = rsa.Encrypt(rjndl.Key, False)

    ' Create byte arrays to contain
    ' the length values of the key and IV.
    Dim LenK() As Byte = New Byte((4) - 1) {}
    Dim LenIV() As Byte = New Byte((4) - 1) {}
    Dim lKey As Integer = keyEncrypted.Length
    LenK = BitConverter.GetBytes(lKey)
    Dim lIV As Integer = rjndl.IV.Length
    LenIV = BitConverter.GetBytes(lIV)

    ' Write the following to the FileStream
    ' for the encrypted file (outFs):
    ' - length of the key
    ' - length of the IV
    ' - ecrypted key
    ' - the IV
    ' - the encrypted cipher content
    ' Change the file's extension to ".enc"

    Dim outFile As String = (EncrFolder _
                + (inFile.Substring(0, inFile.LastIndexOf(".")) + ".enc"))

    Using outFs As FileStream = New FileStream(outFile, FileMode.Create)

        outFs.Write(LenK, 0, 4)
        outFs.Write(LenIV, 0, 4)
        outFs.Write(keyEncrypted, 0, lKey)
        outFs.Write(rjndl.IV, 0, lIV)

        ' Now write the cipher text using
        ' a CryptoStream for encrypting.
        Using outStreamEncrypted As CryptoStream = New CryptoStream(outFs, transform, CryptoStreamMode.Write)
            ' By encrypting a chunk at
            ' a time, you can save memory
            ' and accommodate large files.
            Dim count As Integer = 0
            Dim offset As Integer = 0

            ' blockSizeBytes can be any arbitrary size.
            Dim blockSizeBytes As Integer = (rjndl.BlockSize / 8)
            Dim data() As Byte = New Byte((blockSizeBytes) - 1) {}
            Dim bytesRead As Integer = 0
            Using inFs As FileStream = New FileStream(inFile, FileMode.Open)
                Do
                    count = inFs.Read(data, 0, blockSizeBytes)
                    offset = (offset + count)
                    outStreamEncrypted.Write(data, 0, count)
                    bytesRead = (bytesRead + blockSizeBytes)
                Loop Until (count = 0)

                outStreamEncrypted.FlushFinalBlock()
                inFs.Close()
            End Using
            outStreamEncrypted.Close()
        End Using
        outFs.Close()
    End Using
End Sub
private void EncryptFile(string inFile)
{

    // Create instance of Rijndael for
    // symetric encryption of the data.
    RijndaelManaged rjndl = new RijndaelManaged();
    rjndl.KeySize = 256;
    rjndl.BlockSize = 256;
    rjndl.Mode = CipherMode.CBC;
    ICryptoTransform transform = rjndl.CreateEncryptor();

    // Use RSACryptoServiceProvider to
    // enrypt the Rijndael key.
    byte[] keyEncrypted = rsa.Encrypt(rjndl.Key, false);

    // Create byte arrays to contain
    // the length values of the key and IV.
    byte[] LenK = new byte[4];
    byte[] LenIV = new byte[4];

    int lKey = keyEncrypted.Length;
    LenK = BitConverter.GetBytes(lKey);
    int lIV = rjndl.IV.Length;
    LenIV = BitConverter.GetBytes(lIV);

    // Write the following to the FileStream
    // for the encrypted file (outFs):
    // - length of the key
    // - length of the IV
    // - ecrypted key
    // - the IV
    // - the encrypted cipher content

   // Change the file's extension to ".enc"
    string outFile = EncrFolder + inFile.Substring(0, inFile.LastIndexOf(".")) + ".enc";

    using (FileStream outFs = new FileStream(outFile, FileMode.Create))
    {

            outFs.Write(LenK, 0, 4);
            outFs.Write(LenIV, 0, 4);
            outFs.Write(keyEncrypted, 0, lKey);
            outFs.Write(rjndl.IV, 0, lIV);

            // Now write the cipher text using
            // a CryptoStream for encrypting.
            using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
            {

                // By encrypting a chunk at
                // a time, you can save memory
                // and accommodate large files.
                int count = 0;
                int offset = 0;

                // blockSizeBytes can be any arbitrary size.
                int blockSizeBytes = rjndl.BlockSize / 8;
                byte[] data = new byte[blockSizeBytes];
                int bytesRead = 0;

                using (FileStream inFs = new FileStream(inFile, FileMode.Open))
                {
                    do
                    {
                        count = inFs.Read(data, 0, blockSizeBytes);
                        offset += count;
                        outStreamEncrypted.Write(data, 0, count);
                        bytesRead += blockSizeBytes;
                    }
                    while (count > 0);
                inFs.Close();
                }
                outStreamEncrypted.FlushFinalBlock();
                outStreamEncrypted.Close();
            }
            outFs.Close();
    }

}

Descriptografar um arquivo

Essa tarefa envolve dois métodos, o evento método do manipulador para o Decrypt File botão (buttonEncryptFile_Click) e o DecryptFile método. O primeiro método exibe uma caixa de diálogo para selecionar um arquivo e passa nome de arquivo para o segundo método, que executa a descriptografia.

The Decrypt método faz o seguinte:

  1. Cria um RijndaelManaged algoritmo simétrico para descriptografar o conteúdo.

  2. Lê os oito primeiros byte do FileStream do pacote criptografado em matrizes de byte para obter os comprimentos de chave criptografada e o IV.

  3. Extrai a chave e IV do pacote de criptografia em matrizes de byte.

  4. Cria um RSACryptoServiceProvider objeto para descriptografar o RijndaelManaged chave.

  5. Usa um CryptoStream objeto ler e descriptografar seção de texto cifrado o FileStream criptografia de pacote, em blocos de bytes, para o FileStream objeto para o arquivo descriptografar ed. Quando terminar, a descriptografia é concluída.

Adicione o código a seguir sistema autônomo a Click manipulador de eventos para o Decrypt File botão.

Private Sub buttonDecryptFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonDecryptFile.Click
    If rsa Is Nothing Then
        MsgBox("Key not set.")
    Else
        ' Display a dialog box to select the encrypted file.
        OpenFileDialog2.InitialDirectory = EncrFolder
        If (OpenFileDialog2.ShowDialog = Windows.Forms.DialogResult.OK) Then
            Try
                Dim fName As String = OpenFileDialog2.FileName
                If (Not (fName) Is Nothing) Then
                    Dim fi As FileInfo = New FileInfo(fName)
                    Dim name As String = fi.Name
                    DecryptFile(name)
                End If
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End If
    End If
End Sub
private void buttonDecryptFile_Click(object sender, EventArgs e)
{
    if (rsa == null)
        MessageBox.Show("Key not set.");
    else
    {
        // Display a dialog box to select the encrypted file.
        openFileDialog2.InitialDirectory = EncrFolder;
        if (openFileDialog2.ShowDialog() == DialogResult.OK)
        {
            string fName = openFileDialog2.FileName;
            if (fName != null)
            {
                FileInfo fi = new FileInfo(fName);
                string name = fi.Name;
                DecryptFile(name);
            }
        }
    }
}

Adicione o seguinte DecryptFile método para o formulário.

Private Sub DecryptFile(ByVal inFile As String)
    ' Create instance of Rijndael for
    ' symetric decryption of the data.
    Dim rjndl As RijndaelManaged = New RijndaelManaged
    rjndl.KeySize = 256
    rjndl.BlockSize = 256
    rjndl.Mode = CipherMode.CBC

    ' Create byte arrays to get the length of
    ' the encrypted key and IV.
    ' These values were stored as 4 bytes each
    ' at the beginning of the encrypted package.
    Dim LenK() As Byte = New Byte(4 - 1) {}
    Dim LenIV() As Byte = New Byte(4 - 1) {}

    ' Construct the file name for the decrypted file.
    Dim outFile As String = (DecrFolder _
                + (inFile.Substring(0, inFile.LastIndexOf(".")) + ".txt"))

    ' Use FileStream objects to read the encrypted
    ' file (inFs) and save the decrypted file (outFs).
    Using inFs As FileStream = New FileStream((EncrFolder + inFile), FileMode.Open)

        inFs.Seek(0, SeekOrigin.Begin)
        inFs.Read(LenK, 0, 3)
        inFs.Seek(4, SeekOrigin.Begin)
        inFs.Read(LenIV, 0, 3)

        Dim lengthK As Integer = BitConverter.ToInt32(LenK, 0)
        Dim lengthIV As Integer = BitConverter.ToInt32(LenIV, 0)
        Dim startC As Integer = (lengthK + lengthIV + 8)
        Dim lenC As Integer = (CType(inFs.Length, Integer) - startC)
        Dim KeyEncrypted() As Byte = New Byte(lengthK - 1) {}
        Dim IV() As Byte = New Byte(lengthIV - 1) {}

        ' Extract the key and IV
        ' starting from index 8
        ' after the length values.
        inFs.Seek(8, SeekOrigin.Begin)
        inFs.Read(KeyEncrypted, 0, lengthK)
        inFs.Seek(8 + lengthK, SeekOrigin.Begin)
        inFs.Read(IV, 0, lengthIV)
        Dim KeyDecrypted() As Byte = rsa.Decrypt(KeyEncrypted, False)

        ' Decrypt the key.
        Dim transform As ICryptoTransform = rjndl.CreateDecryptor(KeyDecrypted, IV)

        ' Decrypt the cipher text from
        ' from the FileSteam of the encrypted
        ' file (inFs) into the FileStream
        ' for the decrypted file (outFs).
        Using outFs As FileStream = New FileStream(outFile, FileMode.Create)
            Dim count As Integer = 0
            Dim offset As Integer = 0

            ' blockSizeBytes can be any arbitrary size.
            Dim blockSizeBytes As Integer = (rjndl.BlockSize / 8)
            Dim data() As Byte = New Byte(blockSizeBytes - 1) {}
            ' By decrypting a chunk a time,
            ' you can save memory and
            ' accommodate large files.
            ' Start at the beginning
            ' of the cipher text.
            inFs.Seek(startC, SeekOrigin.Begin)
            Using outStreamDecrypted As CryptoStream = New CryptoStream(outFs, transform, CryptoStreamMode.Write)
                Do
                    count = inFs.Read(data, 0, blockSizeBytes)
                    offset = (offset + count)
                    outStreamDecrypted.Write(data, 0, count)
                Loop Until (count = 0)

                outStreamDecrypted.FlushFinalBlock()
                outStreamDecrypted.Close()
            End Using
            outFs.Close()
        End Using
        inFs.Close()
    End Using
End Sub
private void DecryptFile(string inFile)
{

    // Create instance of Rijndael for
    // symetric decryption of the data.
    RijndaelManaged rjndl = new RijndaelManaged();
    rjndl.KeySize = 256;
    rjndl.BlockSize = 256;
    rjndl.Mode = CipherMode.CBC;
    rjndl.Padding = PaddingMode.None;

    // Create byte arrays to get the length of
    // the encrypted key and IV.
    // These values were stored as 4 bytes each
    // at the beginning of the encrypted package.
    byte[] LenK = new byte[4];
    byte[] LenIV = new byte[4];

    // Consruct the file name for the decrypted file.
    string outFile = DecrFolder + inFile.Substring(0, inFile.LastIndexOf(".")) + ".txt";

    // Use FileStream objects to read the encrypted
    // file (inFs) and save the decrypted file (outFs).
    using (FileStream inFs = new FileStream(EncrFolder + inFile, FileMode.Open))
    {

        inFs.Seek(0, SeekOrigin.Begin);
        inFs.Seek(0, SeekOrigin.Begin);
        inFs.Read(LenK, 0, 3);
        inFs.Seek(4, SeekOrigin.Begin);
        inFs.Read(LenIV, 0, 3);

        // Convert the lengths to integer values.
        int lenK = BitConverter.ToInt32(LenK, 0);
        int lenIV = BitConverter.ToInt32(LenIV, 0);

        // Determine the start postition of
        // the ciphter text (startC)
        // and its length(lenC).
        int startC = lenK + lenIV + 8;
        int lenC = (int)inFs.Length - startC;

        // Create the byte arrays for
        // the encrypted Rijndael key,
        // the IV, and the cipher text.
        byte[] KeyEncrypted = new byte[lenK];
        byte[] IV = new byte[lenIV];

        // Extract the key and IV
        // starting from index 8
        // after the length values.
        inFs.Seek(8, SeekOrigin.Begin);
        inFs.Read(KeyEncrypted, 0, lenK);
        inFs.Seek(8 + lenK, SeekOrigin.Begin);
        inFs.Read(IV, 0, lenIV);

        // Use RSACryptoServiceProvider
        // to decrypt the Rijndael key.
        byte[] KeyDecrypted = rsa.Decrypt(KeyEncrypted, false);

        // Decrypt the key.
        ICryptoTransform transform = rjndl.CreateDecryptor(KeyDecrypted, IV);

        // Decrypt the cipher text from
        // from the FileSteam of the encrypted
        // file (inFs) into the FileStream
        // for the decrypted file (outFs).
        using (FileStream outFs = new FileStream(outFile, FileMode.Create))
        {

            int count = 0;
            int offset = 0;

            // blockSizeBytes can be any arbitrary size.
            int blockSizeBytes = rjndl.BlockSize / 8;
            byte[] data = new byte[blockSizeBytes];


            // By decrypting a chunk a time,
            // you can save memory and
            // accommodate large files.

            // Start at the beginning
            // of the cipher text.
            inFs.Seek(startC, SeekOrigin.Begin);
            using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
            {
                do
                {
                    count = inFs.Read(data, 0, blockSizeBytes);
                    offset += count;
                    outStreamDecrypted.Write(data, 0, count);

                }
                while (count > 0);

                outStreamDecrypted.FlushFinalBlock();
                outStreamDecrypted.Close();
            }
            outFs.Close();
        }
        inFs.Close();
    }

}

Exportando uma chave pública

Esta tarefa salva a chave criada pelo Create Keys botão para um arquivo. Ele exporta somente os parâmetros públicos.

Esta tarefa simula o cenário de Alice dando Bob sua chave pública para que ele pode criptografar arquivos para ela.Ele e outros usuários que possuem essa chave pública não poderá descriptografá-los porque eles não têm o emparelhar de chaves completo com emparelharticular emparelharâmetros.

Adicione o código a seguir sistema autônomo a Click manipulador de eventos para o Export Public Key botão (buttonExportPublicKey_Click).

Private Sub buttonExportPublicKey_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonExportPublicKey.Click
    ' Save the public key created by the RSA
    ' to a file. Caution, persisting the
    ' key to a file is a security risk.
    Dim sw As StreamWriter = New StreamWriter(PubKeyFile)
    sw.Write(rsa.ToXmlString(False))
    sw.Close()
End Sub
void buttonExportPublicKey_Click(object sender, System.EventArgs e)
{
    // Save the public key created by the RSA
    // to a file. Caution, persisting the
    // key to a file is a security risk.
    StreamWriter sw = new StreamWriter(PubKeyFile);
    sw.Write(rsa.ToXmlString(false));
    sw.Close();
}

Importar uma chave pública

Esta tarefa carrega a chave com parâmetros apenas públicos, sistema autônomo criada pelo Export Public Key botão e o define sistema autônomo o nome do contêiner de chave.

Esta tarefa simula o cenário do Bob carregando a chave de Alice com somente parâmetros públicos para que ele pode criptografar arquivos para ela.

Adicione o código a seguir sistema autônomo a Click manipulador de eventos para o Import Public Key botão (buttonImportPublicKey_Click).

Private Sub buttonImportPublicKey_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonImportPublicKey.Click
    Dim sr As StreamReader = New StreamReader(PubKeyFile)
    cspp.KeyContainerName = keyName
    rsa = New RSACryptoServiceProvider(cspp)
    Dim keytxt As String = sr.ReadToEnd
    rsa.FromXmlString(keytxt)
    rsa.PersistKeyInCsp = True
    If rsa.PublicOnly = True Then
        Label1.Text = "Key: " + cspp.KeyContainerName + " - Public Only"
    Else
        Label1.Text = "Key: " + cspp.KeyContainerName + " - Full Key Pair"
    End If
    sr.Close()
End Sub
void buttonImportPublicKey_Click(object sender, System.EventArgs e)
{
    StreamReader sr = new StreamReader(PubKeyFile);
    cspp.KeyContainerName = keyName;
    rsa = new RSACryptoServiceProvider(cspp);
    string keytxt = sr.ReadToEnd();
    rsa.FromXmlString(keytxt);
    rsa.PersistKeyInCsp = true;
    if (rsa.PublicOnly == true)
        label1.Text = "Key: " + cspp.KeyContainerName + " - Public Only";
    else
        label1.Text = "Key: " + cspp.KeyContainerName + " - Full Key Pair";
    sr.Close();
}

Obtendo uma chave particular

Esta tarefa define o nome de contêiner de chave para o nome da chave criada usando o Create Keys botão. O contêiner de chave conterá o emparelhar de chaves completo com parâmetros particulares.

Esta tarefa simula o cenário de Alice, usando sua chave particular para descriptografar arquivos criptografados por Bob.

Adicione o código a seguir sistema autônomo a Click manipulador de eventos para o Get Private Key botão (buttonGetPrivateKey_Click).

Private Sub buttonGetPrivateKey_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles buttonGetPrivateKey.Click
    cspp.KeyContainerName = keyName
    rsa = New RSACryptoServiceProvider(cspp)
    rsa.PersistKeyInCsp = True
    If rsa.PublicOnly = True Then
        Label1.Text = "Key: " + cspp.KeyContainerName + " - Public Only"
    Else
        Label1.Text = "Key: " + cspp.KeyContainerName + " - Full Key Pair"
    End If
End Sub
private void buttonGetPrivateKey_Click(object sender, EventArgs e)
{
    cspp.KeyContainerName = keyName;

    rsa = new RSACryptoServiceProvider(cspp);
    rsa.PersistKeyInCsp = true;

    if (rsa.PublicOnly == true)
        label1.Text = "Key: " + cspp.KeyContainerName + " - Public Only";
    else
        label1.Text = "Key: " + cspp.KeyContainerName + " - Full Key Pair";

}

Testando o aplicativo

Após você ter criado o aplicativo, execute os seguintes cenários de testes.

Para criar chaves, criptografar e descriptografar

  1. Clique no botão Create Keys.O rótulo exibe o nome da chave e mostra que é um emparelhar de chaves completo.

  2. Clique no botão Export Public Key.Observe que a exportação os parâmetros de chave públicos não altera a chave corrente.

  3. clicar no Encrypt File botão e selecionar um arquivo.

  4. Click the Decrypt Filebutton and select the file just encrypted.

  5. Examine o arquivo descriptografado apenas.

  6. fechar o aplicativo e reiniciá-lo para testar recuperar recipientes chave persistentes no seguinte cenário.

Para criptografar usando a chave pública

  1. Clique no botão Import Public Key.O rótulo exibe o nome da chave e mostra que é pública apenas.

  2. clicar no Encrypt File botão e selecionar um arquivo.

  3. Click the Decrypt Filebutton and select the file just encrypted.Isso irá falhar porque você deve ter a chave particular para descriptografar.

Este cenário demonstra que somente a chave pública para criptografar um arquivo para outra pessoa.Normalmente essa pessoa teria proporcionam somente a chave pública e a chave particular para decodificação de retenção.

Para descriptografar usando a chave particular

  1. Clique no botão Get Private Key.O rótulo exibe o nome da chave e mostra se ele é o emparelhar de chaves completo.

  2. clicar no Decrypt File botão e selecionar o arquivo criptografado apenas. Isso terá êxito porque você tem o emparelhar de chaves completo para descriptografar.

Consulte também

Outros recursos

Tarefas de criptografia

Serviços de criptografia