SymmetricAlgorithm SymmetricAlgorithm SymmetricAlgorithm SymmetricAlgorithm Class

定义

表示所有对称算法的实现都必须从中继承的抽象基类。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类的类使用称为加密块链接(CBC)的链接模式,这需要使用 key (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.

RijndaelManagedDESCryptoServiceProvider、和TripleDESCryptoServiceProvider是对称算法的实现。 RC2CryptoServiceProviderRijndaelManaged, 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 ,以释放与该对象关联的所有托管资源和非托管资源。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 占用的非托管资源,还可以另外再释放托管资源。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.

允许 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 的浅表副本。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 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the SymmetricAlgorithm and optionally releases the managed resources.

适用于

另请参阅