CryptoStreamとは? わかりやすく解説

CryptoStream クラス

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

名前空間: System.Security.Cryptography
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

<ComVisibleAttribute(True)> _
Public Class CryptoStream
    Inherits Stream
    Implements IDisposable
[ComVisibleAttribute(true)] 
public class CryptoStream : Stream, IDisposable
[ComVisibleAttribute(true)] 
public ref class CryptoStream : public
 Stream, IDisposable
/** @attribute ComVisibleAttribute(true) */ 
public class CryptoStream extends Stream implements
 IDisposable
ComVisibleAttribute(true) 
public class CryptoStream extends
 Stream implements IDisposable
解説解説
使用例使用例

CryptoStream を使用して文字列を暗号化する方法を次の例に示します。このメソッドでは、RijndaelManaged クラスで Key と初期化ベクタ (IV) が指定されています。

Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Module RijndaelSample

    Sub Main()
        Try
            ' Create a new Rijndael object to generate a key
            ' and initialization vector (IV).
            Dim RijndaelAlg As Rijndael = Rijndael.Create

            ' Create a string to encrypt.
            Dim sData As String
 = "Here is some data to encrypt."
            Dim FileName As String
 = "CText.txt"

            ' Encrypt text to a file using the file name, key, and IV.
            EncryptTextToFile(sData, FileName, RijndaelAlg.Key, RijndaelAlg.IV)

            ' Decrypt the text from a file using the file name, key,
 and IV.
            Dim Final As String
 = DecryptTextFromFile(FileName, RijndaelAlg.Key, RijndaelAlg.IV)

            ' Display the decrypted string to the console.
            Console.WriteLine(Final)
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try

        Console.ReadLine()

    End Sub


    Sub EncryptTextToFile(ByVal Data As
 String, ByVal FileName As
 String, ByVal Key() As Byte, ByVal IV() As Byte)
        Try
            ' Create or open the specified file.
            Dim fStream As FileStream = File.Open(FileName,
 FileMode.OpenOrCreate)

            ' Create a new Rijndael object.
            Dim RijndaelAlg As Rijndael = Rijndael.Create

            ' Create a CryptoStream using the FileStream 
            ' and the passed key and initialization vector (IV).
            Dim cStream As New
 CryptoStream(fStream, _
                                           RijndaelAlg.CreateEncryptor(Key, IV),
 _
                                           CryptoStreamMode.Write)

            ' Create a StreamWriter using the CryptoStream.
            Dim sWriter As New
 StreamWriter(cStream)

            Try

                ' Write the data to the stream 
                ' to encrypt it.
                sWriter.WriteLine(Data)
            Catch e As Exception

                Console.WriteLine("An error occurred: {0}",
 e.Message)

            Finally

                ' Close the streams and
                ' close the file.
                sWriter.Close()
                cStream.Close()
                fStream.Close()

            End Try
        Catch e As CryptographicException
            Console.WriteLine("A Cryptographic error occurred:
 {0}", e.Message)
        Catch e As UnauthorizedAccessException
            Console.WriteLine("A file error occurred: {0}",
 e.Message)
        End Try
    End Sub


    Function DecryptTextFromFile(ByVal FileName
 As String, ByVal Key()
 As Byte, ByVal IV() As Byte) As String
        Try
            ' Create or open the specified file. 
            Dim fStream As FileStream = File.Open(FileName,
 FileMode.OpenOrCreate)

            ' Create a new Rijndael object.
            Dim RijndaelAlg As Rijndael = Rijndael.Create

            ' Create a CryptoStream using the FileStream 
            ' and the passed key and initialization vector (IV).
            Dim cStream As New
 CryptoStream(fStream, _
                                            RijndaelAlg.CreateDecryptor(Key, IV),
 _
                                            CryptoStreamMode.Read)

            ' Create a StreamReader using the CryptoStream.
            Dim sReader As New
 StreamReader(cStream)

            ' Read the data from the stream 
            ' to decrypt it.
            Dim val As String
 = Nothing

            Try

                val = sReader.ReadLine()

            Catch e As Exception
                Console.WriteLine("An Cerror occurred: {0}",
 e.Message)
            Finally
                ' Close the streams and
                ' close the file.
                sReader.Close()
                cStream.Close()
                fStream.Close()


            End Try

            ' Return the string. 
            Return val

        Catch e As CryptographicException
            Console.WriteLine("A Cryptographic error occurred:
 {0}", e.Message)
            Return Nothing
        Catch e As UnauthorizedAccessException
            Console.WriteLine("A file error occurred: {0}",
 e.Message)
            Return Nothing
        End Try
    End Function
End Module
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

class RijndaelSample
{

    static void Main()
    {
        try
        {
            // Create a new Rijndael object to generate a key
            // and initialization vector (IV).
            Rijndael RijndaelAlg = Rijndael.Create();

            // Create a string to encrypt.
            string sData = "Here is some data to encrypt.";
            string FileName = "CText.txt";

            // Encrypt text to a file using the file name, key, and
 IV.
            EncryptTextToFile(sData, FileName, RijndaelAlg.Key, RijndaelAlg.IV);

            // Decrypt the text from a file using the file name, key,
 and IV.
            string Final = DecryptTextFromFile(FileName, RijndaelAlg.Key,
 RijndaelAlg.IV);

            // Display the decrypted string to the console.
            Console.WriteLine(Final);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        Console.ReadLine();
    }

    public static void EncryptTextToFile(String
 Data, String FileName, byte[] Key, byte[] IV)
    {
        try
        {
            // Create or open the specified file.
            FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);

            // Create a new Rijndael object.
            Rijndael RijndaelAlg = Rijndael.Create();

            // Create a CryptoStream using the FileStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream(fStream,
                RijndaelAlg.CreateEncryptor(Key, IV),
                CryptoStreamMode.Write);

            // Create a StreamWriter using the CryptoStream.
            StreamWriter sWriter = new StreamWriter(cStream);

            try
            {
                // Write the data to the stream 
                // to encrypt it.
                sWriter.WriteLine(Data);
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: {0}", e.Message);
            }
            finally
            {
                // Close the streams and
                // close the file.
                sWriter.Close();
                cStream.Close();
                fStream.Close();
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine("A file error occurred: {0}", e.Message);
        }

    }

    public static string
 DecryptTextFromFile(String FileName, byte[] Key, byte[] IV)
    {
        try
        {
            // Create or open the specified file. 
            FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);

            // Create a new Rijndael object.
            Rijndael RijndaelAlg = Rijndael.Create();

            // Create a CryptoStream using the FileStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream(fStream,
                RijndaelAlg.CreateDecryptor(Key, IV),
                CryptoStreamMode.Read);

            // Create a StreamReader using the CryptoStream.
            StreamReader sReader = new StreamReader(cStream);

            string val = null;

            try
            {
                // Read the data from the stream 
                // to decrypt it.
                val = sReader.ReadLine();


            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: {0}", e.Message);
            }
            finally
            {

                // Close the streams and
                // close the file.
                sReader.Close();
                cStream.Close();
                fStream.Close();
            }

            // Return the string. 
            return val;
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine("A file error occurred: {0}", e.Message);
            return null;
        }
    }
}
継承階層継承階層
System.Object
   System.MarshalByRefObject
     System.IO.Stream
      System.Security.Cryptography.CryptoStream
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバの場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

CryptoStream コンストラクタ

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

名前空間: System.Security.Cryptography
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Sub New ( _
    stream As Stream, _
    transform As ICryptoTransform, _
    mode As CryptoStreamMode _
)
Dim stream As Stream
Dim transform As ICryptoTransform
Dim mode As CryptoStreamMode

Dim instance As New CryptoStream(stream,
 transform, mode)
public CryptoStream (
    Stream stream,
    ICryptoTransform transform,
    CryptoStreamMode mode
)
public:
CryptoStream (
    Stream^ stream, 
    ICryptoTransform^ transform, 
    CryptoStreamMode mode
)
public CryptoStream (
    Stream stream, 
    ICryptoTransform transform, 
    CryptoStreamMode mode
)
public function CryptoStream (
    stream : Stream, 
    transform : ICryptoTransform, 
    mode : CryptoStreamMode
)

パラメータ

stream

暗号変換を実行する対象のストリーム。

transform

指定したストリームで実行する暗号変換。

mode

CryptoStreamMode 値の 1 つ。

解説解説

Stream から派生する任意のオブジェクトを stream パラメータに渡すことができます。HashAlgorithm などの ICryptoTransform を実装する任意のオブジェクトを transform パラメータに渡すことができます。

プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
CryptoStream クラス
CryptoStream メンバ
System.Security.Cryptography 名前空間
その他の技術情報
暗号サービス

CryptoStream プロパティ


CryptoStream メソッド


パブリック メソッドパブリック メソッド

( プロテクト メソッド も参照)
  名前 説明
パブリック メソッド BeginRead  非同期の読み込み動作を開始します。 ( Stream から継承されます。)
パブリック メソッド BeginWrite  非同期の書き込み操作を開始します。 ( Stream から継承されます。)
パブリック メソッド Clear CryptoStream によって使用されているすべてのリソースを解放します。
パブリック メソッド Close  現在のストリームを閉じ、現在のストリームに関連付けられているすべてのリソース (ソケット、ファイル ハンドルなど) を解放します。 ( Stream から継承されます。)
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信に使用するプロキシの生成に必要な情報をすべて格納しているオブジェクトを作成します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド Dispose オーバーロードされます。  
パブリック メソッド EndRead  保留中の非同期読み取りが完了するまで待機します。 ( Stream から継承されます。)
パブリック メソッド EndWrite  非同期書き込み操作を終了します。 ( Stream から継承されます。)
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 ( Object から継承されます。)
パブリック メソッド Flush オーバーライドされます。 ストリームに対応するすべてのバッファをクリアし、バッファ内のデータを基になるデバイスに書き込みます。
パブリック メソッド FlushFinalBlock 基になるデータ ソースまたはリポジトリをバッファの現在の状態に更新し、その後でバッファをクリアします。
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 ( Object から継承されます。)
パブリック メソッド GetLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、現在の有効期間サービス オブジェクトを取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 ( Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、有効期間サービス オブジェクトを取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド Read オーバーライドされます。 現在の CryptoStream からバイト シーケンスを読み取り、読み取ったバイト数の分だけストリーム内の位置を進めます。
パブリック メソッド ReadByte  ストリームから 1 バイトを読み取り、ストリーム内の位置を 1 バイト進めます。ストリームの末尾の場合は -1 を返します。 ( Stream から継承されます。)
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 ( Object から継承されます。)
パブリック メソッド Seek オーバーライドされます。 現在のストリーム内の位置を設定します。
パブリック メソッド SetLength オーバーライドされます。 現在のストリームの長さを設定します。
パブリック メソッド Synchronized  指定した Stream オブジェクトをラップするスレッド セーフな (同期された) ラッパーを作成します。 ( Stream から継承されます。)
パブリック メソッド ToString  現在の Object を表す String を返します。 ( Object から継承されます。)
パブリック メソッド Write オーバーライドされます。 バイト シーケンスを現在の CryptoStream に書き込み、書き込んだバイト数の分だけストリーム内の現在位置を進めます。
パブリック メソッド WriteByte  ストリームの現在位置にバイトを書き込み、ストリームの位置を 1 バイトだけ進めます。 ( Stream から継承されます。)
プロテクト メソッドプロテクト メソッド
明示的インターフェイスの実装明示的インターフェイスの実装
  名前 説明
インターフェイスの明示的な実装 System.IDisposable.Dispose CryptoStream によって使用されているアンマネージ リソースを解放し、オプションでマネージ リソースも解放します。
参照参照

関連項目

CryptoStream クラス
System.Security.Cryptography 名前空間

その他の技術情報

暗号サービス

CryptoStream メンバ

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

CryptoStream データ型で公開されるメンバを以下の表に示します。


パブリック コンストラクタパブリック コンストラクタ
パブリック プロパティパブリック プロパティ
パブリック メソッドパブリック メソッド
( プロテクト メソッド も参照)
  名前 説明
パブリック メソッド BeginRead  非同期の読み込み動作を開始します。 (Stream から継承されます。)
パブリック メソッド BeginWrite  非同期の書き込み操作を開始します。 (Stream から継承されます。)
パブリック メソッド Clear CryptoStream によって使用されているすべてのリソースを解放します。
パブリック メソッド Close  現在のストリームを閉じ、現在のストリームに関連付けられているすべてのリソース (ソケット、ファイル ハンドルなど) を解放します。 (Stream から継承されます。)
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信に使用するプロキシの生成に必要な情報をすべて格納しているオブジェクトを作成します。 (MarshalByRefObject から継承されます。)
パブリック メソッド Dispose オーバーロードされます。  
パブリック メソッド EndRead  保留中の非同期読み取りが完了するまで待機します。 (Stream から継承されます。)
パブリック メソッド EndWrite  非同期書き込み操作を終了します。 (Stream から継承されます。)
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 (Object から継承されます。)
パブリック メソッド Flush オーバーライドされます。 ストリームに対応するすべてのバッファをクリアし、バッファ内のデータを基になるデバイスに書き込みます。
パブリック メソッド FlushFinalBlock 基になるデータ ソースまたはリポジトリをバッファの現在の状態に更新し、その後でバッファをクリアします。
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 (Object から継承されます。)
パブリック メソッド GetLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、現在の有効期間サービス オブジェクトを取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 (Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象のインスタンスの有効期間ポリシーを制御する、有効期間サービス オブジェクトを取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド Read オーバーライドされます。 現在の CryptoStream からバイト シーケンスを読み取り、読み取ったバイト数の分だけストリーム内の位置を進めます。
パブリック メソッド ReadByte  ストリームから 1 バイトを読み取り、ストリーム内の位置を 1 バイト進めます。ストリームの末尾の場合は -1 を返します。 (Stream から継承されます。)
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 (Object から継承されます。)
パブリック メソッド Seek オーバーライドされます。 現在のストリーム内の位置を設定します。
パブリック メソッド SetLength オーバーライドされます。 現在のストリームの長さを設定します。
パブリック メソッド Synchronized  指定した Stream オブジェクトをラップするスレッド セーフな (同期された) ラッパーを作成します。 (Stream から継承されます。)
パブリック メソッド ToString  現在の Object を表す String を返します。 (Object から継承されます。)
パブリック メソッド Write オーバーライドされます。 バイト シーケンスを現在の CryptoStream に書き込み、書き込んだバイト数の分だけストリーム内の現在位置を進めます。
パブリック メソッド WriteByte  ストリームの現在位置にバイトを書き込み、ストリームの位置を 1 バイトだけ進めます。 (Stream から継承されます。)
プロテクト メソッドプロテクト メソッド
明示的インターフェイスの実装明示的インターフェイスの実装
  名前 説明
インターフェイスの明示的な実装 System.IDisposable.Dispose CryptoStream によって使用されているアンマネージ リソースを解放し、オプションでマネージ リソースも解放します。
参照参照

関連項目

CryptoStream クラス
System.Security.Cryptography 名前空間

その他の技術情報

暗号サービス



英和和英テキスト翻訳

英語⇒日本語日本語⇒英語

辞書ショートカット

すべての辞書の索引

「CryptoStream」の関連用語

CryptoStreamのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



CryptoStreamのページの著作権

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2026 Microsoft.All rights reserved.

©2026 GRAS Group, Inc.RSS