다음을 통해 공유


SymmetricAlgorithm 클래스

모든 대칭 알고리즘의 구현에서 상속해야 하는 추상 기본 클래스를 나타냅니다.

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

구문

‘선언
<ComVisibleAttribute(True)> _
Public MustInherit Class SymmetricAlgorithm
    Implements IDisposable
‘사용 방법
Dim instance As SymmetricAlgorithm
[ComVisibleAttribute(true)] 
public abstract class SymmetricAlgorithm : IDisposable
[ComVisibleAttribute(true)] 
public ref class SymmetricAlgorithm abstract : IDisposable
/** @attribute ComVisibleAttribute(true) */ 
public abstract class SymmetricAlgorithm implements IDisposable
ComVisibleAttribute(true) 
public abstract class SymmetricAlgorithm implements IDisposable

설명

SymmetricAlgorithm 클래스에서 파생되는 클래스는 키(Key)와 초기화 벡터(IV)를 사용하는 CBC(Cipher Block Chaining)라고 하는 체인 모드를 사용하여 데이터에 암호화 변환을 수행합니다. SymmetricAlgorithm 클래스 중 한 클래스를 사용하여 암호화된 데이터를 해독하려면 Key 속성과 IV 속성을 암호화에 사용된 값과 같은 값으로 설정해야 합니다. 대칭 알고리즘을 유용하게 사용하려면 송신자와 수신자에게만 비밀 키를 알려야 합니다.

RijndaelManaged , DESCryptoServiceProvider , RC2CryptoServiceProviderTripleDESCryptoServiceProvider는 대칭 알고리즘을 구현한 것입니다.

파생 클래스를 사용하는 경우에는 개체 사용을 마친 후 단순히 가비지 수집을 실행하는 것만으로는 보안이 충분하게 보장되지 않습니다. 개체를 해제하기 전에 해당 개체에 대해 Clear 메서드를 명시적으로 호출하여 개체 내의 모든 중요한 데이터를 깨끗하게 지워야 합니다. 가비지 수집은 수집된 개체의 내용을 지우지 않고 단순히 메모리를 재할당할 수 있음을 표시할 뿐입니다. 그러므로 가비지 수집으로 수집된 개체 내에 포함된 데이터가 할당되지 않은 메모리의 메모리 힙에 그대로 남아 있을 수 있습니다. 암호화 개체의 경우 이 데이터에는 키 데이터나 일반 텍스트 블록과 같은 중요한 정보가 들어 있을 수 있습니다.

중요한 데이터를 보유하는 .NET Framework의 모든 암호화 클래스는 Clear 메서드를 구현합니다. Clear 메서드를 호출하면 이 메서드는 개체를 안전하게 가비지 수집할 수 있도록 개체 내의 모든 중요한 데이터를 0으로 덮어쓴 다음 개체를 해제합니다. 개체를 0으로 덮어쓰고 해제한 후에는 disposing 매개 변수를 True로 설정한 상태에서 Dispose 메서드를 호출하여 개체와 관련된 관리되는 리소스와 관리되지 않는 리소스를 모두 삭제해야 합니다.

상속자 참고 사항 SymmetricAlgorithm 클래스에서 상속하는 경우 CreateDecryptor, CreateEncryptor, GenerateIVGenerateKey 멤버를 재정의해야 합니다.

예제

다음 코드 예제에서는 지정된 Key 속성과 초기화 벡터(IV)를 통해 RijndaelManaged 클래스를 사용하여 inName에서 지정한 파일을 암호화하고 outName에서 지정한 파일에 암호화된 결과를 출력합니다. 메서드에 대한 desKeydesIV 매개 변수는 8바이트 배열입니다. 이 예제를 실행하려면 고급 암호화 팩이 설치되어 있어야 합니다.

Private Shared Sub EncryptData(inName As String, outName As String, _
rijnKey() As Byte, rijnIV() As Byte)

    'Create the file streams to handle the input and output files.
    Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
    Dim fout As New FileStream(outName, FileMode.OpenOrCreate, _
       FileAccess.Write)
    fout.SetLength(0)
    
    'Create variables to help with read and write.
    Dim bin(100) As Byte 'This is intermediate storage for the encryption.
    Dim rdlen As Long = 0 'This is the total number of bytes written.
    Dim totlen As Long = fin.Length 'Total length of the input file.
    Dim len As Integer 'This is the number of bytes to be written at a time.
    'Creates the default implementation, which is RijndaelManaged.
    Dim rijn As SymmetricAlgorithm = SymmetricAlgorithm.Create()
    Dim encStream As New CryptoStream(fout, _
       rijn.CreateEncryptor(rijnKey, rijnIV), CryptoStreamMode.Write)
    
    Console.WriteLine("Encrypting...")
    
    'Read from the input file, then encrypt and write to the output file.
    While rdlen < totlen
        len = fin.Read(bin, 0, 100)
        encStream.Write(bin, 0, len)
        rdlen = Convert.ToInt32(rdlen + len)
        Console.WriteLine("{0} bytes processed", rdlen)
    End While
    
    encStream.Close()
fout.Close()
fin.Close()
End Sub
private static void EncryptData(String inName, String outName, byte[] rijnKey, byte[] rijnIV)
 {    
     //Create the file streams to handle the input and output files.
     FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
     FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
     fout.SetLength(0);
       
     //Create variables to help with read and write.
     byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
     long rdlen = 0;              //This is the total number of bytes written.
     long totlen = fin.Length;    //This is the total length of the input file.
     int len;                     //This is the number of bytes to be written at a time.
 
     SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); //Creates the default implementation, which is RijndaelManaged.         
     CryptoStream encStream = new CryptoStream(fout, rijn.CreateEncryptor(rijnKey, rijnIV), CryptoStreamMode.Write);
                
     Console.WriteLine("Encrypting...");
 
     //Read from the input file, then encrypt and write to the output file.
     while(rdlen < totlen)
     {
         len = fin.Read(bin, 0, 100);
         encStream.Write(bin, 0, len);
         rdlen = rdlen + len;
         Console.WriteLine("{0} bytes processed", rdlen);
     }
 
     encStream.Close();  
     fout.Close();
     fin.Close();                   
 }
void EncryptData( String^ inName, String^ outName, array<Byte>^rijnKey, array<Byte>^rijnIV )
{
   
   //Create the file streams to handle the input and output files.
   FileStream^ fin = gcnew FileStream( inName,FileMode::Open,FileAccess::Read );
   FileStream^ fout = gcnew FileStream( outName,FileMode::OpenOrCreate,FileAccess::Write );
   fout->SetLength( 0 );
   
   //Create variables to help with read and write.
   array<Byte>^bin = gcnew array<Byte>(100);
   long rdlen = 0; //This is the total number of bytes written.

   long totlen = (long)fin->Length; //This is the total length of the input file.

   int len; //This is the number of bytes to be written at a time.

   SymmetricAlgorithm^ rijn = SymmetricAlgorithm::Create(); //Creates the default implementation, which is RijndaelManaged.         

   CryptoStream^ encStream = gcnew CryptoStream( fout,rijn->CreateEncryptor( rijnKey, rijnIV ),CryptoStreamMode::Write );
   Console::WriteLine( "Encrypting..." );
   
   //Read from the input file, then encrypt and write to the output file.
   while ( rdlen < totlen )
   {
      len = fin->Read( bin, 0, 100 );
      encStream->Write( bin, 0, len );
      rdlen = rdlen + len;
      Console::WriteLine( "{0} bytes processed", rdlen );
   }

   encStream->Close();
   fout->Close();
   fin->Close();
}
private static void EncryptData(String inName, String outName,
    ubyte rijnKey[], ubyte rijnIV[])
{
    //Create the file streams to handle the input and output files.
    FileStream fin = new FileStream(inName, FileMode.Open,
        FileAccess.Read);
    FileStream fout = new FileStream(outName, FileMode.OpenOrCreate,
        FileAccess.Write);
    fout.SetLength(0);

    //Create variables to help with read and write.
    //Following is intermediate storage for the encryption.
    ubyte bin[] = new ubyte[100]; 
    //Following is the total number of bytes written.
    long rdlen = 0;
    //Following is the total length of the input file.
    long totlen = fin.get_Length(); 
    //Following is the number of bytes to be written at a time.
    int len; 

    //Create the default implementation, which is RijndaelManaged.         
    SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); 
    CryptoStream encStream = new CryptoStream(fout, 
        rijn.CreateEncryptor(rijnKey, rijnIV), CryptoStreamMode.Write);

    Console.WriteLine("Encrypting...");

    //Read from the input file, then encrypt and write to the output file.
    while (rdlen < totlen) {
        len = fin.Read(bin, 0, 100);
        encStream.Write(bin, 0, len);
        rdlen = rdlen + len;
        Console.WriteLine("{0} bytes processed", (System.Int64)rdlen);
    }
    encStream.Close();
    fout.Close();
    fin.Close();
} //EncryptData

상속 계층 구조

System.Object
  System.Security.Cryptography.SymmetricAlgorithm
     System.Security.Cryptography.DES
     System.Security.Cryptography.RC2
     System.Security.Cryptography.Rijndael
     System.Security.Cryptography.TripleDES

스레드로부터의 안전성

이 형식의 모든 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에서 지원

참고 항목

참조

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

기타 리소스

암호화 서비스