CryptoStream Classe
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Definisce un flusso che collega i flussi di dati alle trasformazioni crittografiche.
public ref class CryptoStream : System::IO::Stream
public class CryptoStream : System.IO.Stream
[System.Runtime.InteropServices.ComVisible(true)]
public class CryptoStream : System.IO.Stream
type CryptoStream = class
inherit Stream
interface IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type CryptoStream = class
inherit Stream
interface IDisposable
Public Class CryptoStream
Inherits Stream
- Ereditarietà
- Ereditarietà
- Attributi
- Implementazioni
Esempio
Nell'esempio seguente viene illustrato come usare un CryptoStream oggetto per crittografare una stringa. Questo metodo usa la Aes classe con il vettore di inizializzazione e specificato Key (IV).
using System;
using System.IO;
using System.Security.Cryptography;
class AesExample
{
public static void Main()
{
try
{
string original = "Here is some data to encrypt!";
// Create a new instance of the Aes class.
// This generates a new key and initialization vector (IV).
using (Aes myAes = Aes.Create())
{
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes(original, myAes.Key, myAes.IV);
// Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes(encrypted, myAes.Key, myAes.IV);
// Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Round trip: {0}", roundtrip);
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException(nameof(plainText));
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException(nameof(Key));
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException(nameof(IV));
byte[] encrypted;
// Create a Aes object with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create an encryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new())
{
using (CryptoStream csEncrypt = new(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new(csEncrypt))
{
// Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException(nameof(cipherText));
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException(nameof(Key));
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException(nameof(IV));
// Declare the string used to hold the decrypted text.
string plaintext = null;
// Create a Aes object with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new(cipherText))
{
using (CryptoStream csDecrypt = new(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
Imports System.IO
Imports System.Security.Cryptography
Class AesExample
Public Shared Sub Main()
Try
Dim original As String = "Here is some data to encrypt!"
' Create a new instance of the Aes class.
' This generates a new key and initialization vector (IV).
Using myAes = Aes.Create()
' Encrypt the string to an array of bytes.
Dim encrypted As Byte() = EncryptStringToBytes(original, myAes.Key, myAes.IV)
' Decrypt the bytes to a string.
Dim roundtrip As String = DecryptStringFromBytes(encrypted, myAes.Key, myAes.IV)
'Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original)
Console.WriteLine("Round Trip: {0}", roundtrip)
End Using
Catch e As Exception
Console.WriteLine("Error: {0}", e.Message)
End Try
End Sub
Shared Function EncryptStringToBytes(ByVal plainText As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte()
' Check arguments.
If plainText Is Nothing OrElse plainText.Length <= 0 Then
Throw New ArgumentNullException(NameOf(plainText))
End If
If Key Is Nothing OrElse Key.Length <= 0 Then
Throw New ArgumentNullException(NameOf(Key))
End If
If IV Is Nothing OrElse IV.Length <= 0 Then
Throw New ArgumentNullException(NameOf(IV))
End If
Dim encrypted() As Byte
' Create an Aes object with the specified key and IV.
Using aesAlg = Aes.Create()
aesAlg.Key = Key
aesAlg.IV = IV
' Create an encryptor to perform the stream transform.
Dim encryptor As ICryptoTransform = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)
' Create the streams used for encryption.
Using msEncrypt As New MemoryStream()
Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
Using swEncrypt As New StreamWriter(csEncrypt)
' Write all data to the stream.
swEncrypt.Write(plainText)
End Using
encrypted = msEncrypt.ToArray()
End Using
End Using
End Using
' Return the encrypted bytes from the memory stream.
Return encrypted
End Function 'EncryptStringToBytes
Shared Function DecryptStringFromBytes(
ByVal cipherText() As Byte,
ByVal Key() As Byte,
ByVal IV() As Byte) As String
' Check arguments.
If cipherText Is Nothing OrElse cipherText.Length <= 0 Then
Throw New ArgumentNullException(NameOf(cipherText))
End If
If Key Is Nothing OrElse Key.Length <= 0 Then
Throw New ArgumentNullException(NameOf(Key))
End If
If IV Is Nothing OrElse IV.Length <= 0 Then
Throw New ArgumentNullException(NameOf(IV))
End If
' Declare the string used to hold the decrypted text.
Dim plaintext As String = Nothing
' Create an Aes object with the specified key and IV.
Using aesAlg = Aes.Create()
aesAlg.Key = Key
aesAlg.IV = IV
' Create a decryptor to perform the stream transform.
Dim decryptor As ICryptoTransform = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV)
' Create the streams used for decryption.
Using msDecrypt As New MemoryStream(cipherText)
Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
Using srDecrypt As New StreamReader(csDecrypt)
' Read the decrypted bytes from the decrypting stream
' and place them in a string.
plaintext = srDecrypt.ReadToEnd()
End Using
End Using
End Using
End Using
Return plaintext
End Function 'DecryptStringFromBytes
End Class
Commenti
Common Language Runtime usa una progettazione orientata ai flussi per la crittografia. Il nucleo di questa progettazione è CryptoStream. Tutti gli oggetti crittografici che implementano CryptoStream possono essere concatenati con tutti gli oggetti che implementano Stream, in modo che l'output trasmesso da un oggetto possa essere inserito nell'input di un altro oggetto. Il risultato intermedio (l'output del primo oggetto) non deve essere archiviato separatamente.
Importante
In .NET 6 e versioni successive, quando Stream.Read o Stream.ReadAsync viene chiamato con un buffer di lunghezza N, l'operazione viene completata quando almeno 1 byte è stato letto dal flusso o il flusso sottostante che esegue il wrapping restituisce 0 da una chiamata a Read, a indicare che non sono disponibili altri dati. In .NET Framework Stream.Read e Stream.ReadAsync non restituiscono finché tutti i N byte non vengono letti dal flusso o il flusso sottostante restituisce 0 da una chiamata a Read. Se il codice presuppone che i Read metodi non vengano restituiti fino a quando non vengono letti tutti i N byte, potrebbe non riuscire a leggere tutto il contenuto. Per altre informazioni, vedere Letture parziali e zero byte nei flussi.
È consigliabile chiudere sempre in modo esplicito l'oggetto CryptoStream al termine dell'uso chiamando il Clear metodo . In questo modo si scarica il flusso sottostante e vengono elaborati dall'oggetto CryptoStream tutti i blocchi di dati rimanenti. Tuttavia, se si verifica un'eccezione prima di chiamare il Close metodo , l'oggetto CryptoStream potrebbe non essere chiuso. Per assicurarsi che il Close metodo venga sempre chiamato, inserire la chiamata al Clear metodo all'interno del finally blocco di un'istruzione/trycatch.
Questo tipo implementa l'interfaccia IDisposable . Al termine dell'uso del tipo, è necessario eliminarlo direttamente o indirettamente chiamandone Clear il metodo , che a sua volta chiama l'implementazione IDisposable . Per eliminare direttamente il tipo, chiamare il Clear relativo metodo in un try/catch blocco. Per eliminarlo indirettamente, usare un costrutto del linguaggio, ad using esempio (in C#) o Using (in Visual Basic).
Costruttori
| Nome | Descrizione |
|---|---|
| CryptoStream(Stream, ICryptoTransform, CryptoStreamMode, Boolean) |
Inizializza una nuova istanza della classe CryptoStream. |
| CryptoStream(Stream, ICryptoTransform, CryptoStreamMode) |
Inizializza una nuova istanza della CryptoStream classe con un flusso di dati di destinazione, la trasformazione da usare e la modalità del flusso. |
Proprietà
| Nome | Descrizione |
|---|---|
| CanRead |
Ottiene un valore che indica se l'oggetto corrente CryptoStream è leggibile. |
| CanSeek |
Ottiene un valore che indica se è possibile eseguire una ricerca all'interno dell'oggetto corrente CryptoStream. |
| CanTimeout |
Ottiene un valore che determina se il flusso corrente può verificarsi un timeout. (Ereditato da Stream) |
| CanWrite |
Ottiene un valore che indica se l'oggetto corrente CryptoStream è scrivibile. |
| HasFlushedFinalBlock |
Ottiene un valore che indica se il blocco di buffer finale è stato scritto nel flusso sottostante. |
| Length |
Ottiene la lunghezza in byte del flusso. |
| Position |
Ottiene o imposta la posizione all'interno del flusso corrente. |
| ReadTimeout |
Ottiene o imposta un valore, espresso in millisecondi, che determina per quanto tempo il flusso tenterà di leggere prima del timeout. (Ereditato da Stream) |
| WriteTimeout |
Ottiene o imposta un valore, espresso in millisecondi, che determina per quanto tempo il flusso tenterà di scrivere prima del timeout. (Ereditato da Stream) |
Metodi
| Nome | Descrizione |
|---|---|
| BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) |
Avvia un'operazione di lettura asincrona. Prendere invece in considerazione l'uso ReadAsync di . |
| BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) |
Avvia un'operazione di lettura asincrona. Prendere invece in considerazione l'uso ReadAsync(Byte[], Int32, Int32) di . (Ereditato da Stream) |
| BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) |
Avvia un'operazione di scrittura asincrona. Prendere invece in considerazione l'uso WriteAsync di . |
| BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) |
Avvia un'operazione di scrittura asincrona. Prendere invece in considerazione l'uso WriteAsync(Byte[], Int32, Int32) di . (Ereditato da Stream) |
| Clear() |
Rilascia tutte le risorse usate da CryptoStream. |
| Close() |
Chiude il flusso corrente e rilascia tutte le risorse (ad esempio socket e handle di file) associate al flusso corrente. |
| Close() |
Chiude il flusso corrente e rilascia tutte le risorse (ad esempio socket e handle di file) associate al flusso corrente. Invece di chiamare questo metodo, assicurarsi che il flusso sia eliminato correttamente. (Ereditato da Stream) |
| CopyTo(Stream, Int32) |
Legge i byte dal flusso sottostante, applica le trasformazioni crittografiche pertinenti e scrive il risultato nel flusso di destinazione. |
| CopyTo(Stream, Int32) |
Legge i byte dal flusso corrente e li scrive in un altro flusso, usando una dimensione del buffer specificata. Entrambe le posizioni dei flussi sono avanzate in base al numero di byte copiati. (Ereditato da Stream) |
| CopyTo(Stream) |
Legge i byte dal flusso corrente e li scrive in un altro flusso. Entrambe le posizioni dei flussi sono avanzate in base al numero di byte copiati. (Ereditato da Stream) |
| CopyToAsync(Stream, CancellationToken) |
Legge in modo asincrono i byte dal flusso corrente e li scrive in un altro flusso, usando un token di annullamento specificato. Entrambe le posizioni dei flussi sono avanzate in base al numero di byte copiati. (Ereditato da Stream) |
| CopyToAsync(Stream, Int32, CancellationToken) |
Legge in modo asincrono i byte dal flusso sottostante, applica le trasformazioni crittografiche pertinenti e scrive il risultato nel flusso di destinazione. |
| CopyToAsync(Stream, Int32, CancellationToken) |
Legge in modo asincrono i byte dal flusso corrente e li scrive in un altro flusso, usando una dimensione del buffer e un token di annullamento specificati. Entrambe le posizioni dei flussi sono avanzate in base al numero di byte copiati. (Ereditato da Stream) |
| CopyToAsync(Stream, Int32) |
Legge in modo asincrono i byte dal flusso corrente e li scrive in un altro flusso, usando una dimensione del buffer specificata. Entrambe le posizioni dei flussi sono avanzate in base al numero di byte copiati. (Ereditato da Stream) |
| CopyToAsync(Stream) |
Legge in modo asincrono i byte dal flusso corrente e li scrive in un altro flusso. Entrambe le posizioni dei flussi sono avanzate in base al numero di byte copiati. (Ereditato da Stream) |
| CreateObjRef(Type) |
Crea un oggetto che contiene tutte le informazioni pertinenti necessarie per generare un proxy utilizzato per comunicare con un oggetto remoto. (Ereditato da MarshalByRefObject) |
| CreateWaitHandle() |
Obsoleti.
Obsoleti.
Obsoleti.
Alloca un WaitHandle oggetto . (Ereditato da Stream) |
| Dispose() |
Rilascia tutte le risorse usate da Stream. (Ereditato da Stream) |
| Dispose(Boolean) |
Rilascia le risorse non gestite usate da CryptoStream e, facoltativamente, rilascia le risorse gestite. |
| DisposeAsync() |
Rilascia in modo asincrono le risorse non gestite usate da CryptoStream. |
| EndRead(IAsyncResult) |
Attende il completamento della lettura asincrona in sospeso. Prendere invece in considerazione l'uso ReadAsync di . |
| EndRead(IAsyncResult) |
Attende il completamento della lettura asincrona in sospeso. Prendere invece in considerazione l'uso ReadAsync(Byte[], Int32, Int32) di . (Ereditato da Stream) |
| EndWrite(IAsyncResult) |
Termina un'operazione di scrittura asincrona. Prendere invece in considerazione l'uso WriteAsync di . |
| EndWrite(IAsyncResult) |
Termina un'operazione di scrittura asincrona. Prendere invece in considerazione l'uso WriteAsync(Byte[], Int32, Int32) di . (Ereditato da Stream) |
| Equals(Object) |
Determina se l'oggetto specificato è uguale all'oggetto corrente. (Ereditato da Object) |
| Finalize() |
Consente a un oggetto di provare a liberare risorse ed eseguire altre operazioni di pulizia prima che venga recuperata da Garbage Collection. |
| Flush() |
Cancella tutti i buffer per il flusso corrente e determina la scrittura dei dati memorizzati nel buffer nel dispositivo sottostante. |
| FlushAsync() |
Cancella in modo asincrono tutti i buffer per questo flusso e determina la scrittura di tutti i dati memorizzati nel buffer nel dispositivo sottostante. (Ereditato da Stream) |
| FlushAsync(CancellationToken) |
Cancella tutti i buffer per il flusso corrente in modo asincrono, determina la scrittura di tutti i dati memorizzati nel buffer nel dispositivo sottostante e monitora le richieste di annullamento. |
| FlushFinalBlock() |
Aggiorna l'origine dati o il repository sottostante con lo stato corrente del buffer, quindi cancella il buffer. |
| FlushFinalBlockAsync(CancellationToken) |
Aggiorna in modo asincrono l'origine dati o il repository sottostante con lo stato corrente del buffer, quindi cancella il buffer. |
| GetHashCode() |
Funge da funzione hash predefinita. (Ereditato da Object) |
| GetLifetimeService() |
Obsoleti.
Recupera l'oggetto servizio di durata corrente che controlla i criteri di durata per questa istanza. (Ereditato da MarshalByRefObject) |
| GetType() |
Ottiene il Type dell'istanza corrente. (Ereditato da Object) |
| InitializeLifetimeService() |
Obsoleti.
Ottiene un oggetto servizio di durata per controllare i criteri di durata per questa istanza. (Ereditato da MarshalByRefObject) |
| MemberwiseClone() |
Crea una copia superficiale del Objectcorrente. (Ereditato da Object) |
| MemberwiseClone(Boolean) |
Crea una copia superficiale dell'oggetto corrente MarshalByRefObject . (Ereditato da MarshalByRefObject) |
| ObjectInvariant() |
Obsoleti.
Fornisce il supporto per un oggetto Contract. (Ereditato da Stream) |
| Read(Byte[], Int32, Int32) |
Legge una sequenza di byte dal flusso corrente e sposta in avanti la posizione all'interno del flusso in base al numero di byte letti. |
| Read(Span<Byte>) |
Quando sottoposto a override in una classe derivata, legge una sequenza di byte dal flusso corrente e sposta in avanti la posizione all'interno del flusso in base al numero di byte letti. (Ereditato da Stream) |
| ReadAsync(Byte[], Int32, Int32, CancellationToken) |
Legge una sequenza di byte dal flusso corrente in modo asincrono, sposta in avanti la posizione all'interno del flusso in base al numero di byte letti e monitora le richieste di annullamento. |
| ReadAsync(Byte[], Int32, Int32) |
Legge in modo asincrono una sequenza di byte dal flusso corrente e sposta in avanti la posizione all'interno del flusso in base al numero di byte letti. (Ereditato da Stream) |
| ReadAsync(Memory<Byte>, CancellationToken) |
Legge in modo asincrono una sequenza di byte dal flusso corrente, sposta in avanti la posizione all'interno del flusso in base al numero di byte letti e monitora le richieste di annullamento. |
| ReadAsync(Memory<Byte>, CancellationToken) |
Legge in modo asincrono una sequenza di byte dal flusso corrente, sposta in avanti la posizione all'interno del flusso in base al numero di byte letti e monitora le richieste di annullamento. (Ereditato da Stream) |
| ReadAtLeast(Span<Byte>, Int32, Boolean) |
Legge almeno un numero minimo di byte dal flusso corrente e sposta in avanti la posizione all'interno del flusso in base al numero di byte letti. (Ereditato da Stream) |
| ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken) |
Legge in modo asincrono almeno un numero minimo di byte dal flusso corrente, sposta in avanti la posizione all'interno del flusso in base al numero di byte letti e monitora le richieste di annullamento. (Ereditato da Stream) |
| ReadByte() |
Legge un byte dal flusso e sposta in avanti la posizione all'interno del flusso di un byte oppure restituisce -1 se alla fine del flusso. |
| ReadByte() |
Legge un byte dal flusso e sposta in avanti la posizione all'interno del flusso di un byte oppure restituisce -1 se alla fine del flusso. (Ereditato da Stream) |
| ReadExactly(Byte[], Int32, Int32) |
|
| ReadExactly(Span<Byte>) |
Legge i byte dal flusso corrente e sposta in avanti la posizione all'interno del flusso fino a quando l'oggetto |
| ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken) |
Legge |
| ReadExactlyAsync(Memory<Byte>, CancellationToken) |
Legge in modo asincrono i byte dal flusso corrente, sposta la posizione all'interno del flusso fino a quando non |
| Seek(Int64, SeekOrigin) |
Imposta la posizione all'interno del flusso corrente. |
| SetLength(Int64) |
Imposta la lunghezza del flusso corrente. |
| ToString() |
Restituisce una stringa che rappresenta l'oggetto corrente. (Ereditato da Object) |
| Write(Byte[], Int32, Int32) |
Scrive una sequenza di byte nell'oggetto corrente CryptoStream e sposta in avanti la posizione corrente all'interno del flusso in base al numero di byte scritti. |
| Write(ReadOnlySpan<Byte>) |
Quando sottoposto a override in una classe derivata, scrive una sequenza di byte nel flusso corrente e sposta in avanti la posizione corrente all'interno del flusso in base al numero di byte scritti. (Ereditato da Stream) |
| WriteAsync(Byte[], Int32, Int32, CancellationToken) |
Scrive una sequenza di byte nel flusso corrente in modo asincrono, sposta in avanti la posizione corrente all'interno del flusso in base al numero di byte scritti e monitora le richieste di annullamento. |
| WriteAsync(Byte[], Int32, Int32) |
Scrive in modo asincrono una sequenza di byte nel flusso corrente e sposta in avanti la posizione corrente all'interno del flusso in base al numero di byte scritti. (Ereditato da Stream) |
| WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) |
Scrive in modo asincrono una sequenza di byte nel flusso corrente, sposta in avanti la posizione corrente all'interno del flusso in base al numero di byte scritti e monitora le richieste di annullamento. |
| WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) |
Scrive in modo asincrono una sequenza di byte nel flusso corrente, sposta in avanti la posizione corrente all'interno del flusso in base al numero di byte scritti e monitora le richieste di annullamento. (Ereditato da Stream) |
| WriteByte(Byte) |
Scrive un byte nella posizione corrente nel flusso e sposta in avanti la posizione all'interno del flusso di un byte. |
| WriteByte(Byte) |
Scrive un byte nella posizione corrente nel flusso e sposta in avanti la posizione all'interno del flusso di un byte. (Ereditato da Stream) |
Implementazioni dell'interfaccia esplicita
| Nome | Descrizione |
|---|---|
| IDisposable.Dispose() |
Questa API supporta l'infrastruttura del prodotto e non è previsto che venga usata direttamente dal codice. Rilascia le risorse usate dall'istanza corrente della CryptoStream classe . |
Metodi di estensione
| Nome | Descrizione |
|---|---|
| ConfigureAwait(IAsyncDisposable, Boolean) |
Configura il modo in cui verranno eseguite le attese nelle attività restituite da un oggetto eliminabile asincrono. |
| CopyToAsync(Stream, PipeWriter, CancellationToken) |
Legge in modo asincrono i byte da Stream e li scrive nell'oggetto specificato PipeWriterusando un token di annullamento. |