加密数据

执行对称加密和不对称加密时使用不同的过程。 对流可以执行对称加密,因此对称加密对于加密大量的数据很有用。 对少量字节可以执行不对称加密,因此不对称加密对于加密少量的数据很有用。

对称加密

托管对称加密类与称为 CryptoStream 的特殊流类(用于加密读取到流中的数据)一起使用。 CryptoStream 类使用下列参数初始化:一个托管流类、一个实现 ICryptoTransform 接口的类(从实现加密算法的类创建)以及一个 CryptoStreamMode 枚举(描述允许对 CryptoStream 执行的访问类型)。 CryptoStream 类可以使用派生自 Stream 类的任何类初始化,包括 FileStreamMemoryStreamNetworkStream。 使用这些类,可以对各种流对象执行对称加密。

下面的示例阐释如何创建实现 Rijndael 加密算法的 RijndaelManaged 类的一个新实例并使用该实例对 CryptoStream 类执行加密。 在本示例中,使用称为 MyStream 的可以是任何托管流类型的流对象初始化 CryptoStream。 将用于加密的密钥和 IV 传递给 RijndaelManaged 类的 CreateEncryptor 方法。 这里使用了从 RMCrypto 生成的默认密钥和 IV。 最后,传递 CryptoStreamMode.Write 以指定对流的写访问权。

Dim RMCrypto As New RijndaelManaged()
Dim CryptStream As New CryptoStream(MyStream, RMCrypto.CreateEncryptor(RMCrypto.Key, RMCrypto.IV), CryptoStreamMode.Write)
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream CryptStream = new CryptoStream(MyStream, RMCrypto.CreateEncryptor(), CryptoStreamMode.Write);

执行完上面的代码后,将使用 Rijndael 算法加密所有写入到 CryptoStream 对象的数据。

下面的示例显示创建流、加密流、写入流和关闭流的整个过程。 该示例创建一个使用 CryptoStream 类和 RijndaelManaged 类加密的网络流。 它还将使用 StreamWriter 类向加密流中写入一条消息。

注意注意

也可以使用此示例向文件中写入内容。为此,请删除 TcpClient 引用并将 NetworkStream 替换为 FileStream

Imports System
Imports System.IO
Imports System.Security.Cryptography
Imports System.Net.Sockets

Module Module1
Sub Main()
   Try
      'Create a TCP connection to a listening TCP process.
      'Use "localhost" to specify the current computer or
      'replace "localhost" with the IP address of the 
      'listening process. 
      Dim TCP As New TcpClient("localhost", 11000)

      'Create a network stream from the TCP connection. 
      Dim NetStream As NetworkStream = TCP.GetStream()

      'Create a new instance of the RijndaelManaged class
      'and encrypt the stream.
      Dim RMCrypto As New RijndaelManaged()

            Dim Key As Byte() = {&H1, &H2, &H3, &H4, &H5, &H6, &H7, &H8, &H9, &H10, &H11, &H12, &H13, &H14, &H15, &H16}
            Dim IV As Byte() = {&H1, &H2, &H3, &H4, &H5, &H6, &H7, &H8, &H9, &H10, &H11, &H12, &H13, &H14, &H15, &H16}

      'Create a CryptoStream, pass it the NetworkStream, and encrypt 
      'it with the Rijndael class.
      Dim CryptStream As New CryptoStream(NetStream, RMCrypto.CreateEncryptor(Key, IV), CryptoStreamMode.Write)

      'Create a StreamWriter for easy writing to the 
      'network stream.
      Dim SWriter As New StreamWriter(CryptStream)

      'Write to the stream.
      SWriter.WriteLine("Hello World!")

      'Inform the user that the message was written
      'to the stream.
      Console.WriteLine("The message was sent.")

      'Close all the connections.
      SWriter.Close()
      CryptStream.Close()
      NetStream.Close()
      TCP.Close()
   Catch
      'Inform the user that an exception was raised.
      Console.WriteLine("The connection failed.")
   End Try
End Sub
End Module
using System;
using System.IO;
using System.Security.Cryptography;
using System.Net.Sockets;
 
public class main
{
   public static void Main(string[] args)
   {
      try
      {
         //Create a TCP connection to a listening TCP process.
         //Use "localhost" to specify the current computer or
         //replace "localhost" with the IP address of the 
         //listening process.  
         TcpClient TCP = new TcpClient("localhost",11000);
   
         //Create a network stream from the TCP connection. 
         NetworkStream NetStream = TCP.GetStream();

         //Create a new instance of the RijndaelManaged class
         // and encrypt the stream.
         RijndaelManaged RMCrypto = new RijndaelManaged();

         byte[] Key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
         byte[] IV = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};

         //Create a CryptoStream, pass it the NetworkStream, and encrypt 
         //it with the Rijndael class.
         CryptoStream CryptStream = new CryptoStream(NetStream, 
         RMCrypto.CreateEncryptor(Key, IV),   
         CryptoStreamMode.Write);

         //Create a StreamWriter for easy writing to the 
         //network stream.
         StreamWriter SWriter = new StreamWriter(CryptStream);

         //Write to the stream.
         SWriter.WriteLine("Hello World!");

         //Inform the user that the message was written
         //to the stream.
         Console.WriteLine("The message was sent.");

         //Close all the connections.
         SWriter.Close();
         CryptStream.Close();
         NetStream.Close();
         TCP.Close();
      }
      catch
      {
         //Inform the user that an exception was raised.
         Console.WriteLine("The connection failed.");
      }
   }
}

为使上面的示例成功执行,必须有一个进程对 TCPCLient 类中指定的 IP 地址和端口号进行侦听。 如果侦听进程已存在,代码将连接到该侦听进程,使用 Rijndael 对称算法加密流,并将“Hello World!”写入流中。 如果代码执行成功,将把以下文本显示到控制台:

The message was sent.

但是,如果未找到侦听进程或引发了异常,代码将把以下文本显示到控制台:

The connection failed.

不对称加密

不对称算法通常用于加密少量数据,如加密对称密钥和 IV。 通常,执行不对称加密的个人使用由另一方生成的公钥。 .NET Framework 提供 RSACryptoServiceProvider 类就是为了实现此目的。

下面的示例使用公钥信息加密对称公钥和 IV。 初始化表示第三方公钥的两个字节数组。 将 RSAParameters 对象初始化为这些值。 接下来,使用 RSACryptoServiceProvider.ImportParameters 方法将 RSAParameters 对象(连同它表示的公钥)导入到 RSACryptoServiceProvider 中。 最后,加密由 RijndaelManaged 类创建的私钥和 IV。 本示例要求系统安装有 128 位加密。

Imports System
Imports System.Security.Cryptography

Module Module1

    Sub Main()
        'Initialize the byte arrays to the public key information.
      Dim PublicKey As Byte() =  {214, 46, 220, 83, 160, 73, 40, 39, 201, 155, 19,202, 3, 11, 191, 178, 56, 74, 90, 36, 248, 103, 18, 144, 170, 163, 145, 87, 54, 61, 34, 220, 222, 207, 137, 149, 173, 14, 92, 120, 206, 222, 158, 28, 40, 24, 30, 16, 175, 108, 128, 35, 230, 118, 40, 121, 113, 125, 216, 130, 11, 24, 90, 48, 194, 240, 105, 44, 76, 34, 57, 249, 228, 125, 80, 38, 9, 136, 29, 117, 207, 139, 168, 181, 85, 137, 126, 10, 126, 242, 120, 247, 121, 8, 100, 12, 201, 171, 38, 226, 193, 180, 190, 117, 177, 87, 143, 242, 213, 11, 44, 180, 113, 93, 106, 99, 179, 68, 175, 211, 164, 116, 64, 148, 226, 254, 172, 147}

        Dim Exponent As Byte() = {1, 0, 1}

        'Create values to store encrypted symmetric keys.
        Dim EncryptedSymmetricKey() As Byte
        Dim EncryptedSymmetricIV() As Byte

        'Create a new instance of the RSACryptoServiceProvider class.
        Dim RSA As New RSACryptoServiceProvider()

        'Create a new instance of the RSAParameters structure.
        Dim RSAKeyInfo As New RSAParameters()

        'Set RSAKeyInfo to the public key values. 
        RSAKeyInfo.Modulus = PublicKey
        RSAKeyInfo.Exponent = Exponent

        'Import key parameters into RSA.
        RSA.ImportParameters(RSAKeyInfo)

        'Create a new instance of the RijndaelManaged class.
        Dim RM As New RijndaelManaged()

        'Encrypt the symmetric key and IV.
        EncryptedSymmetricKey = RSA.Encrypt(RM.Key, False)
        EncryptedSymmetricIV = RSA.Encrypt(RM.IV, False)
    End Sub

End Module
using System;
using System.Security.Cryptography;

class Class1
{
   static void Main()
   {
      //Initialize the byte arrays to the public key information.
      byte[] PublicKey = {214,46,220,83,160,73,40,39,201,155,19,202,3,11,191,178,56,
            74,90,36,248,103,18,144,170,163,145,87,54,61,34,220,222,
            207,137,149,173,14,92,120,206,222,158,28,40,24,30,16,175,
            108,128,35,230,118,40,121,113,125,216,130,11,24,90,48,194,
            240,105,44,76,34,57,249,228,125,80,38,9,136,29,117,207,139,
            168,181,85,137,126,10,126,242,120,247,121,8,100,12,201,171,
            38,226,193,180,190,117,177,87,143,242,213,11,44,180,113,93,
            106,99,179,68,175,211,164,116,64,148,226,254,172,147};

      byte[] Exponent = {1,0,1};
      
      //Create values to store encrypted symmetric keys.
      byte[] EncryptedSymmetricKey;
      byte[] EncryptedSymmetricIV;

      //Create a new instance of the RSACryptoServiceProvider class.
      RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

      //Create a new instance of the RSAParameters structure.
      RSAParameters RSAKeyInfo = new RSAParameters();

      //Set RSAKeyInfo to the public key values. 
      RSAKeyInfo.Modulus = PublicKey;
      RSAKeyInfo.Exponent = Exponent;

      //Import key parameters into RSA.
      RSA.ImportParameters(RSAKeyInfo);

      //Create a new instance of the RijndaelManaged class.
      RijndaelManaged RM = new RijndaelManaged();

      //Encrypt the symmetric key and IV.
      EncryptedSymmetricKey = RSA.Encrypt(RM.Key, false);
      EncryptedSymmetricIV = RSA.Encrypt(RM.IV, false);
   }
}

请参见

概念

生成加密和解密的密钥

解密数据

加密服务

其他资源

加密任务