Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Nota
Questo articolo si applica a Windows.
Per informazioni sulle ASP.NET Core, vedere ASP.NET Core Protezione dei dati.
Questa procedura dettagliata illustra come crittografare e decrittografare il contenuto di un file. Gli esempi di codice sono progettati per un'applicazione Windows Forms. Questa applicazione non illustra scenari reali, ad esempio l'uso di smart card. Al contrario illustra gli aspetti fondamentali della crittografia e decrittografia.
Questa procedura dettagliata usa le linee guida seguenti per la crittografia:
Usare la classe Aes, un algoritmo simmetrico, per crittografare e decrittografare dati mediante le proprietà Key e IV generate automaticamente.
Usare l'algoritmo RSA asimmetrico per crittografare e decrittografare la chiave ai dati crittografati da Aes. Gli algoritmi asimmetrici sono ideali per più piccole quantità di dati, come ad esempio una chiave.
Nota
Se si desidera proteggere i dati nel computer anziché scambiare contenuto crittografato con altre persone, prendere in considerazione l'uso della ProtectedData classe.
Nella seguente tabella sono riepilogate le attività crittografate in questo argomento.
Attività | Descrizione |
---|---|
Creare un'applicazione Windows Forms Application | Elenca i controlli necessari per l'esecuzione dell'applicazione. |
Dichiarare oggetti globali | Dichiara le variabili del percorso stringa, CspParameters e RSACryptoServiceProvider per avere il contenuto globale della classe Form. |
Creare una chiave asimmetrica | Crea una coppia di chiavi pubblica asimmetrica e privata e lo assegna a un nome del contenitore di chiavi. |
Crittografare un file | Visualizza una finestra di dialogo per selezionare un file per la crittografia e lo crittografa. |
Decrittografare un file | Visualizza una finestra di dialogo per selezionare un file crittografato per la decrittografia e lo decrittografa. |
Ottenere una chiave privata | Ottiene una coppia di chiavi completa usando il nome del contenitore di chiavi. |
Esportare una chiave pubblica | Salva la chiave in un file XML con solo parametri pubblici. |
Importare una chiave pubblica | Carica la chiave da un file XML in un contenitore di chiavi. |
Test dell'applicazione | Elenca le procedure per il test di questa applicazione. |
Prerequisiti
Per completare questa procedura dettagliata, è necessario disporre dei componenti seguenti:
- Riferimenti agli spazi dei nomi System.IO e System.Security.Cryptography.
Creare un'applicazione Windows Forms Application
La maggior parte degli esempi di codice in questa procedura dettagliata sono progettati per essere gestori di eventi per i controlli pulsante. Nella tabella seguente sono elencati i controlli necessari per l'applicazione di esempio e i relativi nomi richiesti per la corrispondenza con gli esempi di codice.
Control | Nome | Proprietà di testo (in base alle necessità) |
---|---|---|
Button | buttonEncryptFile |
Crittografa un file |
Button | buttonDecryptFile |
Decrittografa un file |
Button | buttonCreateAsmKeys |
Crea chiavi |
Button | buttonExportPublicKey |
Esporta una chiave pubblica |
Button | buttonImportPublicKey |
Importa una chiave pubblica |
Button | buttonGetPrivateKey |
Ottiene una chiave privata |
Label | label1 |
Chiave non impostata |
OpenFileDialog | _encryptOpenFileDialog |
|
OpenFileDialog | _decryptOpenFileDialog |
Fare doppio clic sui pulsanti nella finestra di progettazione di Visual Studio per creare i gestori eventi.
Dichiarare oggetti globali
Aggiungere il codice seguente come parte della dichiarazione della classe Form1. Modificare le variabili di stringa per l'ambiente e le preferenze.
// Declare CspParameters and RsaCryptoServiceProvider
// objects with global scope of your Form class.
readonly 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";
' Declare CspParameters and RsaCryptoServiceProvider
' objects with global scope of your Form class.
ReadOnly _cspp As New CspParameters
Dim _rsa As RSACryptoServiceProvider
' Path variables for source, encryption, and
' decryption folders. Must end with a backslash.
Const EncrFolder As String = "c:\Encrypt\"
Const DecrFolder As String = "c:\Decrypt\"
Const SrcFolder As String = "c:\docs\"
' Public key file
Const PubKeyFile As String = "c:\encrypt\rsaPublicKey.txt"
' Key container name for
' private/public key value pair.
Const KeyName As String = "Key01"
Creare una chiave asimmetrica
Questa attività crea una chiave asimmetrica che crittografa e decrittografa la chiave Aes. Questa chiave era usata per crittografare il contenuto e visualizza il nome del contenitore di chiavi nel controllo etichetta.
Aggiungere il codice seguente come gestore eventi Click
per il pulsante Create Keys
(buttonCreateAsmKeys_Click
).
private void buttonCreateAsmKeys_Click(object sender, EventArgs e)
{
// Stores a key pair in the key container.
_cspp.KeyContainerName = KeyName;
_rsa = new RSACryptoServiceProvider(_cspp)
{
PersistKeyInCsp = true
};
label1.Text = _rsa.PublicOnly
? $"Key: {_cspp.KeyContainerName} - Public Only"
: $"Key: {_cspp.KeyContainerName} - Full Key Pair";
}
Private Sub buttonCreateAsmKeys_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonCreateAsmKeys.Click
' Stores a key pair in the key container.
_cspp.KeyContainerName = KeyName
_rsa = New RSACryptoServiceProvider(_cspp) With {
.PersistKeyInCsp = True
}
If _rsa.PublicOnly Then
Label1.Text = $"Key: {_cspp.KeyContainerName} - Public Only"
Else
Label1.Text = $"Key: {_cspp.KeyContainerName} - Full Key Pair"
End If
End Sub
Crittografare un file
Questa attività prevede due metodi: il metodo del gestore eventi per il Encrypt File
pulsante (buttonEncryptFile_Click
) e il EncryptFile
metodo . Il primo metodo visualizza una finestra di dialogo per la selezione di un file e passa il nome file al secondo metodo, che esegue la crittografia.
Il contenuto, la chiave e il vettore di inizializzazione (IV) crittografati vengono tutti salvati in un FileStream, a cui si fa riferimento come pacchetto di crittografia.
Il metodo EncryptFile
esegue le operazioni seguenti:
- Crea un algoritmo simmetrico Aes per crittografare il contenuto.
- Crea un oggetto RSACryptoServiceProvider per crittografare la chiave Aes.
- Usa un oggetto CryptoStream per leggere e crittografare FileStream del file di origine, in blocchi di byte, in un oggetto FileStream di destinazione per il file crittografato.
- Determina le lunghezze della chiave e del vettore di inizializzazione (IV) crittografati e crea matrici di byte dei valori delle relative lunghezze.
- Scrive la chiave, il vettore di inizializzazione (IV) e i valori delle relative lunghezze nel pacchetto di crittografia.
Il pacchetto di crittografia usa il seguente formato:
- Lunghezza chiave, byte 0 - 3
- Lunghezza vettore di inizializzazione, byte 4 - 7
- Chiave crittografata
- IV
- Testo crittografato
È possibile usare le lunghezze della chiave e del vettore di inizializzazione (IV) per determinare i punti iniziali e lunghezze di tutte le parti del pacchetto di crittografia, che quindi può essere usato per decrittografare il file.
Aggiungere il codice seguente come gestore eventi Click
per il pulsante Encrypt File
(buttonEncryptFile_Click
).
private void buttonEncryptFile_Click(object sender, EventArgs e)
{
if (_rsa is null)
{
MessageBox.Show("Key not set.");
}
else
{
// Display a dialog box to select a file to encrypt.
_encryptOpenFileDialog.InitialDirectory = SrcFolder;
if (_encryptOpenFileDialog.ShowDialog() == DialogResult.OK)
{
string fName = _encryptOpenFileDialog.FileName;
if (fName != null)
{
// Pass the file name without the path.
EncryptFile(new FileInfo(fName));
}
}
}
}
Private Sub buttonEncryptFile_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonEncryptFile.Click
If _rsa Is Nothing Then
MsgBox("Key not set.")
Else
' Display a dialog box to select a file to encrypt.
_encryptOpenFileDialog.InitialDirectory = SrcFolder
If _encryptOpenFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
Try
Dim fName As String = _encryptOpenFileDialog.FileName
If (Not (fName) Is Nothing) Then
Dim fInfo As New FileInfo(fName)
' Use just the file name without path.
Dim name As String = fInfo.FullName
EncryptFile(name)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End If
End Sub
Aggiungere il metodo EncryptFile
seguente al form.
private void EncryptFile(FileInfo file)
{
// Create instance of Aes for
// symmetric encryption of the data.
Aes aes = Aes.Create();
ICryptoTransform transform = aes.CreateEncryptor();
// Use RSACryptoServiceProvider to
// encrypt the AES key.
// rsa is previously instantiated:
// rsa = new RSACryptoServiceProvider(cspp);
byte[] keyEncrypted = _rsa.Encrypt(aes.Key, false);
// Create byte arrays to contain
// the length values of the key and IV.
int lKey = keyEncrypted.Length;
byte[] LenK = BitConverter.GetBytes(lKey);
int lIV = aes.IV.Length;
byte[] LenIV = BitConverter.GetBytes(lIV);
// Write the following to the FileStream
// for the encrypted file (outFs):
// - length of the key
// - length of the IV
// - encrypted key
// - the IV
// - the encrypted cipher content
// Change the file's extension to ".enc"
string outFile =
Path.Combine(EncrFolder, Path.ChangeExtension(file.Name, ".enc"));
using (var outFs = new FileStream(outFile, FileMode.Create))
{
outFs.Write(LenK, 0, 4);
outFs.Write(LenIV, 0, 4);
outFs.Write(keyEncrypted, 0, lKey);
outFs.Write(aes.IV, 0, lIV);
// Now write the cipher text using
// a CryptoStream for encrypting.
using (var 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 = aes.BlockSize / 8;
byte[] data = new byte[blockSizeBytes];
int bytesRead = 0;
using (var inFs = new FileStream(file.FullName, FileMode.Open))
{
do
{
count = inFs.Read(data, 0, blockSizeBytes);
offset += count;
outStreamEncrypted.Write(data, 0, count);
bytesRead += blockSizeBytes;
} while (count > 0);
}
outStreamEncrypted.FlushFinalBlock();
}
}
}
Private Sub EncryptFile(ByVal inFile As String)
' Create instance of Aes for
' symmetric encryption of the data.
Dim aes As Aes = Aes.Create()
Dim transform As ICryptoTransform = aes.CreateEncryptor
' Use RSACryptoServiceProvider to
' encrypt the AES key.
Dim keyEncrypted() As Byte = _rsa.Encrypt(aes.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 = aes.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
' - encrypted key
' - the IV
' - the encrypted cipher content
' Change the file's extension to ".enc"
Dim startFileName As Integer = inFile.LastIndexOf("\") + 1
Dim outFile As String = (EncrFolder _
+ (inFile.Substring(startFileName, inFile.LastIndexOf(".") - startFileName) + ".enc"))
Using outFs As New FileStream(outFile, FileMode.Create)
outFs.Write(LenK, 0, 4)
outFs.Write(LenIV, 0, 4)
outFs.Write(keyEncrypted, 0, lKey)
outFs.Write(aes.IV, 0, lIV)
' Now write the cipher text using
' a CryptoStream for encrypting.
Using outStreamEncrypted As 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 = (aes.BlockSize / 8)
Dim data() As Byte = New Byte((blockSizeBytes) - 1) {}
Dim bytesRead As Integer = 0
Using inFs As 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
Decrittografare un file
Per questa attività vengono usati due metodi: il metodo gestore eventi per il pulsante Decrypt File
(buttonDecryptFile_Click
) e il metodo DecryptFile
. Il primo metodo visualizza una finestra di dialogo per la selezione di un file e passa il nome file al secondo metodo, che esegue la decrittografia.
Il metodo Decrypt
esegue le operazioni seguenti:
- Crea un Aes algoritmo simmetrico per decrittografare il contenuto.
- Legge i primi otto byte del pacchetto crittografato FileStream in matrici di byte per ottenere le lunghezze della chiave e del vettore di inizializzazione crittografati.
- Estrae la chiave e il vettore di inizializzazione dal pacchetto di crittografia in matrici di byte.
- Crea un oggetto RSACryptoServiceProvider per decrittografare la chiave Aes.
- Usa un oggetto CryptoStream per leggere e decrittografare la sezione del testo crittografato del pacchetto di crittografia FileStream, in blocchi di byte, nell'oggetto FileStream per il file decrittografato. Quando questa operazione è terminata, la decrittografia è completata.
Aggiungere il codice seguente come gestore eventi Click
per il pulsante Decrypt File
.
private void buttonDecryptFile_Click(object sender, EventArgs e)
{
if (_rsa is null)
{
MessageBox.Show("Key not set.");
}
else
{
// Display a dialog box to select the encrypted file.
_decryptOpenFileDialog.InitialDirectory = EncrFolder;
if (_decryptOpenFileDialog.ShowDialog() == DialogResult.OK)
{
string fName = _decryptOpenFileDialog.FileName;
if (fName != null)
{
DecryptFile(new FileInfo(fName));
}
}
}
}
Private Sub buttonDecryptFile_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonDecryptFile.Click
If _rsa Is Nothing Then
MsgBox("Key not set.")
Else
' Display a dialog box to select the encrypted file.
_decryptOpenFileDialog.InitialDirectory = EncrFolder
If (_decryptOpenFileDialog.ShowDialog = Windows.Forms.DialogResult.OK) Then
Try
Dim fName As String = _decryptOpenFileDialog.FileName
If ((fName) IsNot Nothing) Then
Dim fi As 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
Aggiungere il metodo DecryptFile
seguente al form.
private void DecryptFile(FileInfo file)
{
// Create instance of Aes for
// symmetric decryption of the data.
Aes aes = Aes.Create();
// 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];
// Construct the file name for the decrypted file.
string outFile =
Path.ChangeExtension(file.FullName.Replace("Encrypt", "Decrypt"), ".txt");
// Use FileStream objects to read the encrypted
// file (inFs) and save the decrypted file (outFs).
using (var inFs = new FileStream(file.FullName, FileMode.Open))
{
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 position of
// the cipher text (startC)
// and its length(lenC).
int startC = lenK + lenIV + 8;
int lenC = (int)inFs.Length - startC;
// Create the byte arrays for
// the encrypted Aes 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);
Directory.CreateDirectory(DecrFolder);
// Use RSACryptoServiceProvider
// to decrypt the AES key.
byte[] KeyDecrypted = _rsa.Decrypt(KeyEncrypted, false);
// Decrypt the key.
ICryptoTransform transform = aes.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 (var outFs = new FileStream(outFile, FileMode.Create))
{
int count = 0;
int offset = 0;
// blockSizeBytes can be any arbitrary size.
int blockSizeBytes = aes.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 (var 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();
}
}
}
}
Private Sub DecryptFile(ByVal inFile As String)
' Create instance of Aes for
' symmetric decryption of the data.
Dim aes As Aes = Aes.Create()
' 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 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)
Directory.CreateDirectory(DecrFolder)
' User RSACryptoServiceProvider
' to decrypt the AES key
Dim KeyDecrypted() As Byte = _rsa.Decrypt(KeyEncrypted, False)
' Decrypt the key.
Dim transform As ICryptoTransform = aes.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 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 = (aes.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 New CryptoStream(outFs, transform, CryptoStreamMode.Write)
Do
count = inFs.Read(data, 0, blockSizeBytes)
offset += count
outStreamDecrypted.Write(data, 0, count)
Loop Until (count = 0)
outStreamDecrypted.FlushFinalBlock()
End Using
End Using
End Using
End Sub
Esportare una chiave pubblica
Questa attività salva la chiave creata dal pulsante Create Keys
in un file. Esporta solo i parametri pubblici.
Questa attività simula lo scenario in cui Alice fornisce a Bob la sua chiave pubblica affinché egli possa crittografare i file per Alice. Bob e altri utenti che dispongono di quella chiave pubblica non saranno in grado di decrittografarli poiché non possiedono la coppia di chiavi completa con i parametri privati.
Aggiungere il codice seguente come gestore eventi Click
per il pulsante Export Public Key
(buttonExportPublicKey_Click
).
void buttonExportPublicKey_Click(object sender, EventArgs e)
{
// Save the public key created by the RSA
// to a file. Caution, persisting the
// key to a file is a security risk.
Directory.CreateDirectory(EncrFolder);
using (var sw = new StreamWriter(PubKeyFile, false))
{
sw.Write(_rsa.ToXmlString(false));
}
}
Private Sub buttonExportPublicKey_Click(ByVal sender As Object, ByVal e As 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.
Directory.CreateDirectory(EncrFolder)
Using sw As New StreamWriter(PubKeyFile)
sw.Write(_rsa.ToXmlString(False))
End Using
End Sub
Importare una chiave pubblica
Questa attività carica la chiave con solo parametri pubblici, come creati dal pulsante Export Public Key
e la imposta come nome del contenitore di chiavi.
Questa attività simula lo scenario di Bob che carica la chiave di Alice con solo parametri pubblici in modo che possa crittografare file per conto di Alice.
Aggiungere il codice seguente come gestore eventi Click
per il pulsante Import Public Key
(buttonImportPublicKey_Click
).
void buttonImportPublicKey_Click(object sender, EventArgs e)
{
using (var sr = new StreamReader(PubKeyFile))
{
_cspp.KeyContainerName = KeyName;
_rsa = new RSACryptoServiceProvider(_cspp);
string keytxt = sr.ReadToEnd();
_rsa.FromXmlString(keytxt);
_rsa.PersistKeyInCsp = true;
label1.Text = _rsa.PublicOnly
? $"Key: {_cspp.KeyContainerName} - Public Only"
: $"Key: {_cspp.KeyContainerName} - Full Key Pair";
}
}
Private Sub buttonImportPublicKey_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonImportPublicKey.Click
Using sr As 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 Then
Label1.Text = $"Key: {_cspp.KeyContainerName} - Public Only"
Else
Label1.Text = $"Key: {_cspp.KeyContainerName} - Full Key Pair"
End If
End Using
End Sub
Ottenere una chiave privata
Questa attività imposta il nome del contenitore di chiavi sul nome della chiave creata mediante il pulsante Create Keys
. Il contenitore di chiavi conterrà la coppia di chiavi completa con parametri privati.
Questa attività simula lo scenario di Alice che usa la propria chiave privata per decrittografare file crittografati da Bob.
Aggiungere il codice seguente come gestore eventi Click
per il pulsante Get Private Key
(buttonGetPrivateKey_Click
).
private void buttonGetPrivateKey_Click(object sender, EventArgs e)
{
_cspp.KeyContainerName = KeyName;
_rsa = new RSACryptoServiceProvider(_cspp)
{
PersistKeyInCsp = true
};
label1.Text = _rsa.PublicOnly
? $"Key: {_cspp.KeyContainerName} - Public Only"
: $"Key: {_cspp.KeyContainerName} - Full Key Pair";
}
Private Sub buttonGetPrivateKey_Click(ByVal sender As Object,
ByVal e As EventArgs) Handles buttonGetPrivateKey.Click
_cspp.KeyContainerName = KeyName
_rsa = New RSACryptoServiceProvider(_cspp) With {
.PersistKeyInCsp = True
}
If _rsa.PublicOnly Then
Label1.Text = $"Key: {_cspp.KeyContainerName} - Public Only"
Else
Label1.Text = $"Key: {_cspp.KeyContainerName} - Full Key Pair"
End If
End Sub
Test dell'applicazione
Dopo aver compilato l'applicazione, eseguire gli scenari di test seguenti.
Per creare chiavi, crittografare e decrittografare
- Fare clic sul pulsante
Create Keys
. L'etichetta visualizza il nome della chiave e mostra che è una coppia di chiavi completa. - Fare clic sul pulsante
Export Public Key
. Si noti che l'esportazione dei parametri della chiave pubblica non modifica la chiave corrente. - Fare clic sul pulsante
Encrypt File
e selezionare un file. - Fare clic sul pulsante
Decrypt File
e selezionare il file appena crittografato. - Esaminare il file appena decrittografato.
- Chiudere l'applicazione e riavviarla per testare il recupero dei contenitori di chiavi persistenti nello scenario successivo.
Per crittografare mediante la chiave pubblica
- Fare clic sul pulsante
Import Public Key
. L'etichetta visualizza il nome della chiave e mostra che è solo pubblica. - Fare clic sul pulsante
Encrypt File
e selezionare un file. - Fare clic sul pulsante
Decrypt File
e selezionare il file appena crittografato. Questa operazione avrà esito negativo perché si deve avere a disposizione la chiave privata per decrittografare.
Questo scenario illustra una situazione in cui si possiede solo la chiave pubblica per crittografare un file per un'altra persona. In genere quella persona potrebbe mettere a disposizione solo la chiave pubblica e mantenere quella privata per la decrittografia.
Per decrittografare mediante la chiave privata
- Fare clic sul pulsante
Get Private Key
. L'etichetta visualizza il nome della chiave e mostra se è la coppia di chiavi completa. - Fare clic sul pulsante
Decrypt File
e selezionare il file appena crittografato. Questa operazione avrà esito positivo perché si possiede la coppia di chiavi completa per decrittografare.
Vedi anche
- Modello di crittografia: descrive il modo in cui la crittografia viene implementata nella libreria di classi di base.
- servizi crittografici
- Crittografia multipiattaforma
- ASP.NET Core protezione dei dati