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) 和初始化向量 (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释放所有托管和非托管资源与对象相关联。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.

适用于

另请参阅