SymmetricAlgorithm SymmetricAlgorithm SymmetricAlgorithm SymmetricAlgorithm Class

定義

表示抽象基底類別,對稱演算法之所有實作 (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
繼承
SymmetricAlgorithmSymmetricAlgorithmSymmetricAlgorithmSymmetricAlgorithm
衍生
屬性
實作

範例

下列程式碼範例會使用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類別使用鏈結的模式,稱為 cipher 區塊鏈結 (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.

RijndaelManagedDESCryptoServiceProviderRC2CryptoServiceProvider,和TripleDESCryptoServiceProvider是對稱演算法的實作。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 和 unmanaged 物件相關聯的資源。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() SymmetricAlgorithm() SymmetricAlgorithm()

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

欄位

BlockSizeValue BlockSizeValue BlockSizeValue BlockSizeValue

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

FeedbackSizeValue FeedbackSizeValue FeedbackSizeValue FeedbackSizeValue

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

IVValue IVValue IVValue IVValue

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

KeySizeValue KeySizeValue KeySizeValue KeySizeValue

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

KeyValue KeyValue KeyValue KeyValue

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

LegalBlockSizesValue LegalBlockSizesValue LegalBlockSizesValue LegalBlockSizesValue

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

LegalKeySizesValue LegalKeySizesValue LegalKeySizesValue LegalKeySizesValue

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

ModeValue ModeValue ModeValue ModeValue

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

PaddingValue PaddingValue PaddingValue PaddingValue

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

屬性

BlockSize BlockSize BlockSize BlockSize

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

FeedbackSize FeedbackSize FeedbackSize FeedbackSize

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

IV IV IV IV

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

Key Key Key Key

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

KeySize KeySize KeySize KeySize

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

LegalBlockSizes LegalBlockSizes LegalBlockSizes LegalBlockSizes

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

LegalKeySizes LegalKeySizes LegalKeySizes LegalKeySizes

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

Mode Mode Mode Mode

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

Padding Padding Padding Padding

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

方法

Clear() Clear() Clear() Clear()

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

Create() Create() Create() Create()

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

Create(String) Create(String) Create(String) Create(String)

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

CreateDecryptor() CreateDecryptor() CreateDecryptor() CreateDecryptor()

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

CreateDecryptor(Byte[], Byte[]) CreateDecryptor(Byte[], Byte[]) CreateDecryptor(Byte[], Byte[]) 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() CreateEncryptor() CreateEncryptor() CreateEncryptor()

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

CreateEncryptor(Byte[], Byte[]) CreateEncryptor(Byte[], Byte[]) CreateEncryptor(Byte[], Byte[]) 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() Dispose() Dispose() Dispose()

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

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

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

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Object)
Finalize() Finalize() Finalize() 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() GenerateIV() GenerateIV() GenerateIV()

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

GenerateKey() GenerateKey() GenerateKey() GenerateKey()

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

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

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

(Inherited from Object)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
ToString() ToString() ToString() ToString()

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

(Inherited from Object)
ValidKeySize(Int32) ValidKeySize(Int32) ValidKeySize(Int32) ValidKeySize(Int32)

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

明確介面實作

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

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

適用於

另請參閱