SymmetricAlgorithm 類別

定義

表示抽象基底類別,對稱演算法之所有實作 (Implementation) 必須從它繼承。Represents the abstract base class from which all implementations of symmetric algorithms must inherit.

public ref class SymmetricAlgorithm abstract : IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class SymmetricAlgorithm : IDisposable
type SymmetricAlgorithm = class
    interface IDisposable
Public MustInherit Class SymmetricAlgorithm
Implements IDisposable
繼承
SymmetricAlgorithm
衍生
屬性
實作

範例

下列程式碼範例會使用RijndaelManaged具有指定Key屬性和初始化向量(IV)的類別來加密所inName指定的檔案,並將加密的結果輸出至所指定outName的檔案。.The following code example uses the RijndaelManaged class with the specified Key property and initialization vector (IV) to encrypt a file specified by inName, and outputs the encrypted result to the file specified by outName. 方法desKeydesIV和參數為8位元組陣列。The desKey and desIV parameters to the method are 8-byte arrays. 您必須安裝高加密套件,才能執行此範例。You must have the high encryption pack installed to run this example.

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, 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();                   
 }
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

備註

衍生自SymmetricAlgorithm類別的類別會使用稱為「加密區塊連結」(CBC)的連結模式,這需要金鑰(Key)和初始化向量(IV)來執行資料的密碼編譯轉換。The classes that derive from the SymmetricAlgorithm class use a chaining mode called cipher block chaining (CBC), which requires a key (Key) and an initialization vector (IV) to perform cryptographic transformations on data. 若要解密使用其中一個SymmetricAlgorithm類別加密的資料,您必須Key將屬性和IV屬性設定為用於加密的相同值。To decrypt data that was encrypted using one of the SymmetricAlgorithm classes, you must set the Key property and the IV property to the same values that were used for encryption. 若要讓對稱演算法有用,只有傳送者和接收者才必須知道秘密金鑰。For a symmetric algorithm to be useful, the secret key must be known only to the sender and the receiver.

RijndaelManagedDESCryptoServiceProviderRC2CryptoServiceProviderTripleDESCryptoServiceProvider是對稱演算法的實施。RijndaelManaged, DESCryptoServiceProvider, RC2CryptoServiceProvider, and TripleDESCryptoServiceProvider are implementations of symmetric algorithms.

請注意,使用衍生類別時,不是從安全性的觀點來看,只要在使用完物件之後強制執行垃圾收集。Note that when using derived classes, it is not enough, from a security perspective, to simply force a garbage collection after you have finished using the object. 您必須在物件上Clear明確呼叫方法,以在釋放物件之前,將其中的任何機密資料都設為零。You must explicitly call the Clear method on the object to zero out any sensitive data within the object before it is released. 請注意,垃圾收集並不會將所收集物件的內容零出來,而只會將記憶體標示為可供重新配置。Note that garbage collection does not zero out the contents of collected objects but simply marks the memory as available for reallocation. 因此,垃圾收集物件內所包含的資料可能仍會出現在未配置記憶體的記憶體堆積中。Thus the data contained within a garbage collected object may still be present in the memory heap in unallocated memory. 在密碼編譯物件的案例中,此資料可能包含機密資訊,例如金鑰資料或純文字區塊。In the case of cryptographic objects, this data could contain sensitive information such as key data or a block of plain text.

.NET Framework 中保存敏感性資料的所有密碼編譯類別都會執行Clear方法。All cryptographic classes in the .NET Framework that hold sensitive data implement a Clear method. 當呼叫時, Clear方法會以零覆寫物件中的所有機密資料,然後釋放物件,以便安全地進行垃圾收集。When called, the Clear method overwrites all sensitive data within the object with zeros and then releases the object so that it can be safely garbage collected. 當物件已清空並釋出時,您應該呼叫Dispose方法disposing ,並將參數設定為True ,以處置與該物件相關聯的所有 managed 和非受控資源。When the object has been zeroed and released, you should then call the Dispose method with the disposing parameter set to True to dispose of all managed and unmanaged resources associated with the object.

給繼承者的注意事項

SymmetricAlgorithm當您從類別繼承時,您必須覆寫下列成員: CreateDecryptor(Byte[], Byte[])CreateEncryptor(Byte[], Byte[])GenerateIV()和。 GenerateKey()When you inherit from the SymmetricAlgorithm class, you must override the following members: CreateDecryptor(Byte[], Byte[]), CreateEncryptor(Byte[], Byte[]), GenerateIV(), and GenerateKey().

建構函式

SymmetricAlgorithm()

初始化 SymmetricAlgorithm 類別的新執行個體。Initializes a new instance of the SymmetricAlgorithm class.

欄位

BlockSizeValue

表示密碼編譯作業的區塊大小,以位元為單位。Represents the block size, in bits, of the cryptographic operation.

FeedbackSizeValue

表示密碼編譯作業的回饋大小,以位元為單位。Represents the feedback size, in bits, of the cryptographic operation.

IVValue

表示對稱演算法的初始化向量 (IV)。Represents the initialization vector (IV) for the symmetric algorithm.

KeySizeValue

表示對稱演算法使用之秘密金鑰的大小,以位元為單位。Represents the size, in bits, of the secret key used by the symmetric algorithm.

KeyValue

表示對稱演算法的秘密金鑰。Represents the secret key for the symmetric algorithm.

LegalBlockSizesValue

指定對稱演算法所支援的區塊大小,以位元為單位。Specifies the block sizes, in bits, that are supported by the symmetric algorithm.

LegalKeySizesValue

指定對稱演算法所支援的金鑰大小,以位元為單位。Specifies the key sizes, in bits, that are supported by the symmetric algorithm.

ModeValue

表示對稱演算法中使用的密碼模式。Represents the cipher mode used in the symmetric algorithm.

PaddingValue

表示對稱演算法中使用的填補模式。Represents the padding mode used in the symmetric algorithm.

屬性

BlockSize

取得或設定密碼編譯作業的區塊大小,以位元為單位。Gets or sets the block size, in bits, of the cryptographic operation.

FeedbackSize

取得或設定密碼編譯作業的回饋大小,以位元為單位。Gets or sets the feedback size, in bits, of the cryptographic operation.

IV

取得或設定對稱演算法的初始化向量 (IV)。Gets or sets the initialization vector (IV) for the symmetric algorithm.

Key

取得或設定對稱演算法的秘密金鑰。Gets or sets the secret key for the symmetric algorithm.

KeySize

取得或設定對稱演算法使用之秘密金鑰的大小,以位元為單位。Gets or sets the size, in bits, of the secret key used by the symmetric algorithm.

LegalBlockSizes

取得對稱演算法所支援的區塊大小,以位元為單位。Gets the block sizes, in bits, that are supported by the symmetric algorithm.

LegalKeySizes

取得對稱演算法所支援的金鑰大小,以位元為單位。Gets the key sizes, in bits, that are supported by the symmetric algorithm.

Mode

取得或設定對稱演算法的作業模式。Gets or sets the mode for operation of the symmetric algorithm.

Padding

取得或設定對稱演算法中使用的填補模式。Gets or sets the padding mode used in the symmetric algorithm.

方法

Clear()

釋放 SymmetricAlgorithm 類別所使用的所有資源。Releases all resources used by the SymmetricAlgorithm class.

Create()

建立用來執行對稱演算法的預設密碼編譯物件。Creates a default cryptographic object used to perform the symmetric algorithm.

Create(String)

建立用來執行對稱演算法之指定密碼編譯物件。Creates the specified cryptographic object used to perform the symmetric algorithm.

CreateDecryptor()

使用目前的 Key 屬性和初始化向量 (IV),建立對稱解密子物件。Creates a symmetric decryptor object with the current Key property and initialization vector (IV).

CreateDecryptor(Byte[], Byte[])

在衍生類別中覆寫時,使用指定的 Key 屬性和初始化向量 (IV) 建立對稱解密子物件。When overridden in a derived class, creates a symmetric decryptor object with the specified Key property and initialization vector (IV).

CreateEncryptor()

使用目前的 Key 屬性和初始化向量 (IV),建立對稱加密子物件。Creates a symmetric encryptor object with the current Key property and initialization vector (IV).

CreateEncryptor(Byte[], Byte[])

在衍生類別中覆寫時,使用指定的 Key 屬性和初始化向量 (IV) 建立對稱加密子物件。When overridden in a derived class, creates a symmetric encryptor object with the specified Key property and initialization vector (IV).

Dispose()

釋放 SymmetricAlgorithm 類別目前的執行個體所使用的全部資源。Releases all resources used by the current instance of the SymmetricAlgorithm class.

Dispose(Boolean)

釋放 SymmetricAlgorithm 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the SymmetricAlgorithm and optionally releases the managed resources.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
Finalize()

這個成員會覆寫 Finalize(),您可以在該主題中找到更完整的文件。This member overrides Finalize(), and more complete documentation might be available in that topic.

在記憶體回收 (GC) 回收 Object 前,允許 Object 嘗試釋放資源並執行其他清除作業。Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.

GenerateIV()

在衍生類別中覆寫時,產生要用於該演算法的隨機初始化向量 (IV)。When overridden in a derived class, generates a random initialization vector (IV) to use for the algorithm.

GenerateKey()

在衍生類別中覆寫時,產生要用於演算法的隨機金鑰 (Key)。When overridden in a derived class, generates a random key (Key) to use for the algorithm.

GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)
ValidKeySize(Int32)

判斷指定的金鑰大小對目前的演算法是否有效。Determines whether the specified key size is valid for the current algorithm.

明確介面實作

IDisposable.Dispose()

釋放 SymmetricAlgorithm 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the SymmetricAlgorithm and optionally releases the managed resources.

適用於

另請參閱