Tutorial: Crear una aplicación criptográfica
Actualización: noviembre 2007
Este tutorial muestra cómo cifrar y descifrar contenido. Los ejemplos de código están diseñados para una aplicación de formularios Windows Forms. Esta aplicación no muestra escenarios reales, como el uso de tarjetas inteligentes. En su lugar, muestra los principios del cifrado y descifrado.
Este tutorial utiliza las directrices siguientes para el cifrado:
Utiliza la clase RijndaelManaged, un algoritmo simétrico, para cifrar y descifrar los datos mediante su Key e IV generados automáticamente.
Utiliza RSACryptoServiceProvider, un algoritmo asimétrico, para cifrar y descifrar la clave de los datos cifrados por RijndaelManaged. Los algoritmos asimétricos se utilizan especialmente para pequeñas cantidades de datos, como una clave.
Nota: Si desea proteger los datos de su equipo en lugar de intercambiar contenido cifrado con otras personas, considere la posibilidad de usar las clases ProtectedData o ProtectedMemory.
En la tabla siguiente se indican las tareas criptográficas de este tema.
Tarea |
Descripción |
---|---|
Crear una aplicación de formularios Windows Forms. |
Muestra los controles necesarios para ejecutar la aplicación. |
Declarar objetos globales |
Declara las variables de ruta de acceso de cadena, CspParameters y RSACryptoServiceProvider para disponer del contexto global de la clase Form. |
Crear una clave asimétrica |
Crea un par de valores de clave pública y privada asimétrica y lo asigna a un nombre de contenedor de claves. |
Cifrar un archivo |
Muestra un cuadro de diálogo en el que se puede seleccionar un archivo para el cifrado y cifra el archivo. |
Descifrar un archivo |
Muestra un cuadro de diálogo en el que se puede seleccionar un archivo cifrado para su descifrado y descifra el archivo. |
Obtener una clave privada |
Obtiene el par de claves completo mediante el nombre del contenedor de claves. |
Exportar una clave pública |
Guarda la clave en un archivo XML con sólo parámetros públicos. |
Importar una clave pública |
Carga la clave de un archivo XML en el contenedor de claves. |
Probar la aplicación |
Muestra los procedimientos para probar esta aplicación. |
Requisitos previos
Necesita los componentes siguientes para completar este tutorial:
- Referencias a los espacios de nombres System.IO y System.Security.Cryptography.
Crear una aplicación de formularios Windows Forms
La mayoría de los ejemplos de código de este tutorial están diseñados para servir como controladores de eventos de los controles de botón. En la tabla siguiente se muestran los controles necesarios para la aplicación de ejemplo y los nombres que deben tener para que coincidan con los ejemplos de código.
Control |
Nombre |
Propiedad Text (según sea necesario) |
---|---|---|
buttonEncryptFile |
Cifrar archivo |
|
buttonDecryptFile |
Descifrar archivo |
|
buttonCreateAsmKeys |
Crear claves |
|
buttonExportPublicKey |
Exportar clave pública |
|
buttonImportPublicKey |
Importar clave pública |
|
buttonGetPrivateKey |
Obtener clave privada |
|
label1 |
||
openFileDialog1 |
||
openFileDialog2 |
Haga doble clic en los botones del diseñador de Visual Studio para crear sus controladores de eventos.
Declarar objetos globales
Agregue de código siguiente al constructor de Form. Edite las variables de cadena para su entorno y preferencias.
' 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";
Crear una clave asimétrica
Esta tarea crea una clave asimétrica que cifra y descifra la clave RijndaelManaged. Esta clave se utilizó para cifrar el contenido y muestra el nombre del contenedor de claves en el control de etiqueta.
Agregue el código siguiente como el controlador de eventos Click del botón Create Keys (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";
}
Cifrar un archivo
En esta tarea se invocan dos métodos: el método del controlador de eventos del botón Encrypt File (buttonEncryptFile_Click) y el método EncryptFile. El primer método muestra un cuadro de diálogo para seleccionar un archivo y pasa el nombre de archivo al segundo método, que realiza el cifrado.
El contenido cifrado, la clave y el IV (vector de inicialización) se guardan en un FileStream que recibe el nombre de paquete de cifrado.
El método EncryptFile realiza las siguientes operaciones:
Crea un algoritmo simétrico RijndaelManaged para cifrar el contenido.
Crea un objeto RSACryptoServiceProvider para cifrar la clave RijndaelManaged.
Utiliza un objeto CryptoStream para leer y cifrar el FileStream del archivo de código fuente, en bloques de bytes, en un objeto FileStream de destino para el archivo cifrado.
Determina la longitud de la clave cifrada y del IV, y crea matrices de bytes de sus valores de longitud.
Escribe los valores de clave, IV y longitud en el paquete cifrado.
El paquete de cifrado utiliza el formato siguiente:
Longitud de la clave, bytes 0 - 3
Longitud de IV, bytes 4 - 7
Clave cifrada
IV
Texto cifrado
Puede utilizar la longitud de la clave e IV para determinar los puntos iniciales y la longitud de todos los componentes del paquete de cifrado, que podrá utilizar para descifrar el archivo.
Agregue el código siguiente como el controlador de eventos Click del botón Encrypt File (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);
}
}
}
}
Agregue el método EncryptFile siguiente al formulario.
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();
}
}
Descifrar un archivo
En esta tarea se invocan dos métodos, el método del controlador de eventos del botón Decrypt File (buttonEncryptFile_Click) y el método DecryptFile. El primer método muestra un cuadro de diálogo para seleccionar un archivo y pasa el nombre de archivo al segundo método, que realiza el descifrado.
El método Decrypt realiza las siguientes operaciones:
Crea un algoritmo simétrico RijndaelManaged para descifrar el contenido.
Lee los primeros ocho bytes del FileStream del paquete cifrado en matrices de bytes para obtener la longitud de la clave cifrada y del IV.
Extrae la clave y el IV del paquete de cifrado en matrices de bytes.
Crea un objeto RSACryptoServiceProvider para descifrar la clave RijndaelManaged.
Utiliza un objeto CryptoStream para leer y descifrar la sección de texto cifrado del paquete de cifrado FileStream, en bloques de bytes, en el objeto FileStream del archivo descifrado. Cuando esta operación termina, el descifrado finaliza.
Agregue el código siguiente como el controlador de eventos Click del botón Decrypt File.
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);
}
}
}
}
Agregue el método DecryptFile siguiente al formulario.
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();
}
}
Exportar una clave pública
Esta tarea guarda la clave creada por el botón Create Keys en un archivo. Exporta sólo los parámetros públicos.
Esta tarea simula la situación en la que Alicia entrega a Roberto su clave pública para que pueda cifrar los archivos de ella. Él y todos los que tengan esa clave pública no podrán descifrar los archivos porque no tienen el par de claves completo con los parámetros privados.
Agregue el código siguiente como el controlador de eventos Click del botón Export Public Key (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 una clave pública
Esta tarea carga la clave sólo con parámetros públicos, tal y como creó el botón Export Public Key, y la establece en el nombre del contenedor de claves.
Esta tarea simula la situación en la que Roberto carga la clave de Alicia sólo con parámetros públicos para poder cifrar los archivos de ella.
Agregue el código siguiente como el controlador de eventos Click del botón Import Public Key (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();
}
Obtener una clave privada
Esta tarea establece el nombre del contenedor de claves en el nombre de la clave creada con el botón Create Keys. El contenedor de claves incluirá el par de claves completo con parámetros privados.
Esta tarea simula la situación en la que Alicia utiliza su clave privada para descifrar los archivos cifrados por Roberto.
Agregue el código siguiente como el controlador de eventos Click del botón Get Private Key (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";
}
Probar la aplicación
Una vez generada la aplicación, realice los ejemplos de prueba siguientes.
Para crear claves, cifrar y descifrar
Haga clic en el botón Create Keys. La etiqueta muestra el nombre de la clave e indica que se trata del par de claves completo.
Haga clic en el botón Export Public Key. Observe que al exportar los parámetros de clave pública no se cambia la clave actual.
Haga clic en el botón Encrypt File y seleccione un archivo.
Haga clic en el botón Decrypt Filey seleccione el archivo que acaba de cifrar.
Examine el archivo que acaba de descifrar.
Cierre la aplicación y reiníciela para probar cómo se recuperan los contenedores de claves almacenados.
Para cifrar utilizando la clave pública
Haga clic en el botón Import Public Key. La etiqueta muestra el nombre de la clave e indica que sólo es la clave pública.
Haga clic en el botón Encrypt File y seleccione un archivo.
Haga clic en el botón Decrypt Filey seleccione el archivo que acaba de cifrar. Esto producirá un error porque debe tener la clave privada para el descifrado.
Este ejemplo muestra la situación en la que otra persona sólo dispone de la clave pública para cifrar un archivo. Normalmente, esa persona sólo le daría la clave pública y conservaría la clave privada para el descifrado.
Para descifrar utilizando la clave privada
Haga clic en el botón Get Private Key. La etiqueta muestra el nombre de la clave e indica que se trata del par de claves completo.
Haga clic en el botón Decrypt File y seleccione el archivo que acaba de cifrar. El archivo se descifrará correctamente porque tiene el par de claves completo para el descifrado.