다음을 통해 공유


CryptoStream 클래스

데이터 스트림을 암호화 변환에 링크하는 스트림을 정의합니다.

네임스페이스: System.Security.Cryptography
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<ComVisibleAttribute(True)> _
Public Class CryptoStream
    Inherits Stream
    Implements IDisposable
‘사용 방법
Dim instance As CryptoStream
[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입니다. CryptoStream을 구현하는 암호화 개체는 Stream을 구현하는 개체와 연결할 수 있으므로 한 개체로부터의 스트리밍된 출력을 다른 개체에 입력할 수 있습니다. 중간 결과(첫째 개체의 출력)는 별도로 저장하지 않아도 됩니다.

CryptoStream 개체를 사용한 후에는 항상 Close 메서드를 호출하여 해당 개체를 명시적으로 닫아야 합니다. 명시적으로 개체를 닫으면 스트림이 플러시되고, 남아 있는 모든 데이터 블록이 CryptoStream 개체에서 처리됩니다. 하지만 Close 메서드를 호출하기 전에 예외가 발생하면 CryptoStream 개체가 닫히지 않습니다. Close 메서드가 항상 호출되도록 하려면 Close 메서드에 대한 호출을 try/catch 문의 finally 블록에 넣어야 합니다.

예제

다음 예제에서는 CryptoStream을 사용하여 문자열을 암호화하는 방법을 보여 줍니다. 이 메서드는 지정된 Key와 초기화 벡터(IV)를 사용하여 RijndaelManaged 클래스를 사용합니다.

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) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0에서 지원

참고 항목

참조

CryptoStream 멤버
System.Security.Cryptography 네임스페이스

기타 리소스

암호화 서비스