CryptoStream クラス

定義

データ ストリームを暗号変換にリンクするストリームを定義します。

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
継承
CryptoStream
継承
属性
実装

次の例では、 を使用 CryptoStream して文字列を暗号化する方法を示します。 このメソッドは、 Aes 指定された 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

注釈

共通言語ランタイムでは、暗号化にストリーム指向の設計が使用されます。 この設計の中核は です CryptoStream。 を実装 CryptoStream する暗号化オブジェクトは、 を実装 Streamする任意のオブジェクトと一緒にチェーンできるため、あるオブジェクトからのストリーム出力を別のオブジェクトの入力に送ることができます。 中間結果 (最初のオブジェクトからの出力) を個別に格納する必要はありません。

重要

.NET 6 以降のバージョンでは、長さのNバッファーを使用して または Stream.ReadAsync が呼び出されるとStream.Read、ストリームから少なくとも 1 バイトが読み取られた場合、またはラップする基になるストリームが に対する呼び出しReadから 0 を返す場合、操作は完了し、使用できるデータがなくなったことを示します。 .NET 6 より前では、ストリームからすべてのNバイトが読み取られるか、 Stream.ReadStream.ReadAsync基になるストリームから への呼び出しReadから 0 が返されるまで、 が返されませんでした。 コードで、すべてのNバイトが読み取られるまでメソッドが返されないと想定Readしている場合は、すべてのコンテンツの読み取りに失敗する可能性があります。 詳細については、「 ストリームでの部分読み取りと 0 バイト読み取り」を参照してください。

メソッドを呼び出してオブジェクトの使用が完了したら、常にオブジェクトを明示的にClear閉じるCryptoStream必要があります。 これにより、基になるストリームがフラッシュされ、残りのすべてのデータ ブロックが CryptoStream オブジェクトによって処理されます。 ただし、 メソッドを呼び出す前に例外が Close 発生した場合、オブジェクトが CryptoStream 閉じられない可能性があります。 メソッドがClose常に呼び出されるようにするには、ステートメントの/trycatch ブロック内finallyで メソッドをClear呼び出します。

この型は IDisposable インターフェイスを実装します。 型の使用が完了したら、そのメソッドを呼び出して直接または間接的に破棄し、その実装をIDisposable呼び出Clearす必要があります。 直接的に型を破棄するには、try/catch ブロック内で Clear メソッドを呼び出します。 間接的に型を破棄するには、using (C# の場合) または Using (Visual Basic 言語) などの言語構成要素を使用します。

コンストラクター

CryptoStream(Stream, ICryptoTransform, CryptoStreamMode)

暗号化の対象とするデータ ストリーム、使用する変換、およびストリームのモードを指定して、CryptoStream クラスの新しいインスタンスを初期化します。

CryptoStream(Stream, ICryptoTransform, CryptoStreamMode, Boolean)

CryptoStream クラスの新しいインスタンスを初期化します。

プロパティ

CanRead

現在の CryptoStream が読み取り可能かどうかを示す値を取得します。

CanSeek

現在の CryptoStream 内でシークできるかどうかを示す値を取得します。

CanTimeout

現在のストリームがタイムアウトできるかどうかを決定する値を取得します。

(継承元 Stream)
CanWrite

現在の CryptoStream が書き込み可能かどうかを示す値を取得します。

HasFlushedFinalBlock

最後のバッファー ブロックが基になるストリームに書き込まれたかどうかを示す値を取得します。

Length

ストリーム長 (バイト単位) を取得します。

Position

現在のストリーム内の位置を取得または設定します。

ReadTimeout

ストリームがタイムアウト前に読み取りを試みる期間を決定する値 (ミリ秒単位) を取得または設定します。

(継承元 Stream)
WriteTimeout

ストリームがタイムアウト前に書き込みを試行する期間を決定する値 (ミリ秒単位) を取得または設定します。

(継承元 Stream)

メソッド

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

非同期の読み込み動作を開始します。 (代わりに、ReadAsync の使用を検討してください。)

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

非同期の読み込み動作を開始します。 (代わりに、ReadAsync(Byte[], Int32, Int32) の使用を検討してください。)

(継承元 Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

非同期の書き込み操作を開始します。 (代わりに、WriteAsync の使用を検討してください。)

BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

非同期の書き込み操作を開始します。 (代わりに、WriteAsync(Byte[], Int32, Int32) の使用を検討してください。)

(継承元 Stream)
Clear()

CryptoStream によって使用されているすべてのリソースを解放します。

Close()

現在のストリームを閉じ、現在のストリームに関連付けられているすべてのリソース (ソケット、ファイル ハンドルなど) を解放します。

Close()

現在のストリームを閉じ、現在のストリームに関連付けられているすべてのリソース (ソケット、ファイル ハンドルなど) を解放します。 このメソッドを呼び出す代わりに、ストリームが適切に破棄されていることを確認します。

(継承元 Stream)
CopyTo(Stream)

現在のストリームからバイトを読み取り、別のストリームに書き込みます。 どちらのストリーム位置も、コピーされたバイト数だけ進みます。

(継承元 Stream)
CopyTo(Stream, Int32)

基になるストリームからバイトを読み取り、関連する暗号化変換を適用して、結果を宛先ストリームに書き込みます。

CopyTo(Stream, Int32)

指定されたバッファー サイズを使用して、現在のストリームからバイトを読み取り、別のストリームに書き込みます。 どちらのストリーム位置も、コピーされたバイト数だけ進みます。

(継承元 Stream)
CopyToAsync(Stream)

現在のストリームからすべてのバイトを非同期に読み取り、別のストリームに書き込みます。 どちらのストリーム位置も、コピーされたバイト数だけ進みます。

(継承元 Stream)
CopyToAsync(Stream, CancellationToken)

指定されたバッファー サイズを使用して、現在のストリームからバイトを非同期に読み取り、指定されたキャンセル トークンを使用して、別のストリームに書き込みます。 どちらのストリーム位置も、コピーされたバイト数だけ進みます。

(継承元 Stream)
CopyToAsync(Stream, Int32)

指定されたバッファー サイズを使用して、現在のストリームからバイトを非同期に読み取り、別のストリームに書き込みます。 どちらのストリーム位置も、コピーされたバイト数だけ進みます。

(継承元 Stream)
CopyToAsync(Stream, Int32, CancellationToken)

基になるストリームからバイトを非同期に読み取り、関連する暗号化変換を適用して、結果を宛先ストリームに書き込みます。

CopyToAsync(Stream, Int32, CancellationToken)

指定されたバッファー サイズを使用して、現在のストリームからバイトを非同期に読み取り、指定されたバッファー サイズとキャンセル トークンを使用して、別のストリームに書き込みます。 どちらのストリーム位置も、コピーされたバイト数だけ進みます。

(継承元 Stream)
CreateObjRef(Type)

リモート オブジェクトとの通信に使用するプロキシの生成に必要な情報をすべて格納しているオブジェクトを作成します。

(継承元 MarshalByRefObject)
CreateWaitHandle()
古い.
古い.
古い.

WaitHandle オブジェクトを割り当てます。

(継承元 Stream)
Dispose()

Stream によって使用されているすべてのリソースを解放します。

(継承元 Stream)
Dispose(Boolean)

CryptoStream によって使用されているアンマネージド リソースを解放し、オプションでマネージド リソースも解放します。

DisposeAsync()

CryptoStream によって使用されているアンマネージ リソースを非同期に解放します。

DisposeAsync()

Stream によって使用されているアンマネージ リソースを非同期に解放します。

(継承元 Stream)
EndRead(IAsyncResult)

保留中の非同期読み取りが完了するまで待機します。 (代わりに、ReadAsync の使用を検討してください。)

EndRead(IAsyncResult)

保留中の非同期読み取りが完了するまで待機します。 (代わりに、ReadAsync(Byte[], Int32, Int32) の使用を検討してください。)

(継承元 Stream)
EndWrite(IAsyncResult)

非同期書き込み操作を終了します。 (代わりに、WriteAsync の使用を検討してください。)

EndWrite(IAsyncResult)

非同期書き込み操作を終了します。 (代わりに、WriteAsync(Byte[], Int32, Int32) の使用を検討してください。)

(継承元 Stream)
Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
Finalize()

オブジェクトが、ガベージ コレクションによって収集される前に、リソースの解放とその他のクリーンアップ操作の実行を試みることができるようにします。

Flush()

現在のストリームのバッファーをすべてクリアし、バッファー内にあるデータすべてを、基になるデバイスに書き込みます。

FlushAsync()

ストリームに対応するすべてのバッファーを非同期にクリアし、バッファー内のデータを基になるデバイスに書き込みます。

(継承元 Stream)
FlushAsync(CancellationToken)

現在のストリームのすべてのバッファーを非同期にクリアし、バッファー内のデータを基になるデバイスに書き込み、キャンセル要求を監視します。

FlushAsync(CancellationToken)

ストリームに対応するすべてのバッファーを非同期にクリアし、バッファー内のデータを基になるデバイスに書き込み、キャンセル要求を監視します。

(継承元 Stream)
FlushFinalBlock()

基になるデータ ソースまたはリポジトリをバッファーの現在の状態に更新し、その後でバッファーをクリアします。

FlushFinalBlockAsync(CancellationToken)

基になるデータ ソースまたはリポジトリをバッファーの現在の状態に非同期的に更新し、その後でバッファーをクリアします。

GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetLifetimeService()
古い.

対象のインスタンスの有効期間ポリシーを制御する、現在の有効期間サービス オブジェクトを取得します。

(継承元 MarshalByRefObject)
GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
InitializeLifetimeService()
古い.

このインスタンスの有効期間ポリシーを制御する有効期間サービス オブジェクトを取得します。

(継承元 MarshalByRefObject)
MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
MemberwiseClone(Boolean)

現在の MarshalByRefObject オブジェクトの簡易コピーを作成します。

(継承元 MarshalByRefObject)
ObjectInvariant()
古い.

Contract のサポートを提供します。

(継承元 Stream)
Read(Byte[], Int32, Int32)

現在のストリームからバイト シーケンスを読み取り、読み取ったバイト数だけストリーム内の位置を進めます。

Read(Span<Byte>)

派生クラスによってオーバーライドされた場合は、現在のストリームからバイト シーケンスを読み取り、読み取ったバイト数の分だけストリームの位置を進めます。

(継承元 Stream)
ReadAsync(Byte[], Int32, Int32)

現在のストリームからバイト シーケンスを非同期に読み取り、読み取ったバイト数だけストリーム内の位置を進めます。

(継承元 Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

現在のストリームから非同期的にバイト シーケンスを読み取り、読み取ったバイト数だけストリーム内の位置を進め、キャンセル要求を監視します。

ReadAsync(Byte[], Int32, Int32, CancellationToken)

現在のストリームからバイト シーケンスを非同期に読み取り、読み取ったバイト数だけストリーム内の位置を進め、キャンセル要求を監視します。

(継承元 Stream)
ReadAsync(Memory<Byte>, CancellationToken)

現在のストリームからバイト シーケンスを非同期に読み取り、読み取ったバイト数だけストリーム内の位置を進め、キャンセル要求を監視します。

ReadAsync(Memory<Byte>, CancellationToken)

現在のストリームからバイト シーケンスを非同期に読み取り、読み取ったバイト数だけストリーム内の位置を進め、キャンセル要求を監視します。

(継承元 Stream)
ReadAtLeast(Span<Byte>, Int32, Boolean)

現在のストリームから少なくともバイト数を読み取り、ストリーム内の位置を読み取ったバイト数だけ進めます。

(継承元 Stream)
ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken)

現在のストリームから少なくとも最小バイト数を非同期に読み取り、読み取ったバイト数だけストリーム内の位置を進め、キャンセル要求を監視します。

(継承元 Stream)
ReadByte()

ストリームから 1 バイトを読み取り、ストリーム内の位置を 1 バイト進めます。ストリームの末尾の場合は -1 を返します。

ReadByte()

ストリームから 1 バイトを読み取り、ストリーム内の位置を 1 バイト進めます。ストリームの末尾の場合は -1 を返します。

(継承元 Stream)
ReadExactly(Byte[], Int32, Int32)

現在のストリームからバイト数を読み取 count り、ストリーム内の位置を進めます。

(継承元 Stream)
ReadExactly(Span<Byte>)

現在のストリームからバイトを読み取り、 が塗りつぶされるまでストリーム内の位置を buffer 進めます。

(継承元 Stream)
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken)

現在のストリームからバイト数を非同期に読み取 count り、ストリーム内の位置を進め、取り消し要求を監視します。

(継承元 Stream)
ReadExactlyAsync(Memory<Byte>, CancellationToken)

現在のストリームからバイトを非同期に読み取り、 が満たされるまでストリーム内の位置を buffer 進め、取り消し要求を監視します。

(継承元 Stream)
Seek(Int64, SeekOrigin)

現在のストリーム内の位置を設定します。

SetLength(Int64)

現在のストリームの長さを設定します。

ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)
Write(Byte[], Int32, Int32)

バイト シーケンスを現在の CryptoStream に書き込み、書き込んだバイト数の分だけストリーム内の現在位置を進めます。

Write(ReadOnlySpan<Byte>)

派生クラスによってオーバーライドされた場合は、現在のストリームにバイト シーケンスを書き込み、書き込んだバイト数の分だけストリームの現在位置を進めます。

(継承元 Stream)
WriteAsync(Byte[], Int32, Int32)

現在のストリームにバイト シーケンスを非同期に書き込み、書き込んだバイト数だけストリーム内の現在位置を進めます。

(継承元 Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

現在のストリームにバイト シーケンスを非同期で書き込み、書き込んだバイト数だけストリーム内の現在位置を進め、キャンセル要求を監視します。

WriteAsync(Byte[], Int32, Int32, CancellationToken)

現在のストリームにバイト シーケンスを非同期に書き込み、書き込んだバイト数だけストリーム内の現在位置を進め、キャンセル要求を監視します。

(継承元 Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

現在のストリームにバイト シーケンスを非同期に書き込み、書き込んだバイト数だけストリーム内の現在位置を進め、キャンセル要求を監視します。

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

現在のストリームにバイト シーケンスを非同期に書き込み、書き込んだバイト数だけストリーム内の現在位置を進め、キャンセル要求を監視します。

(継承元 Stream)
WriteByte(Byte)

ストリームの現在位置にバイトを書き込み、ストリームの位置を 1 バイトだけ進めます。

WriteByte(Byte)

ストリームの現在位置にバイトを書き込み、ストリームの位置を 1 バイトだけ進めます。

(継承元 Stream)

明示的なインターフェイスの実装

IDisposable.Dispose()

この API は製品インフラストラクチャをサポートします。コードから直接使用するものではありません。

CryptoStream クラスの現在のインスタンスによって使用されているリソースを解放します。

拡張メソッド

ConfigureAwait(IAsyncDisposable, Boolean)

非同期の破棄可能から返されるタスク上での待機がどのように実行されるかを構成します。

適用対象

こちらもご覧ください