ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.2052/cpguide/html/cpconencryptingdata.htm若要加密和解密数据,必须使用具有对数据执行转换的加密算法的密钥。.NET Framework 提供了几个使您能够使用若干标准算法对数据执行加密转换的类。本节描述如何创建和管理密钥,以及如何使用公钥和私钥算法来加密和解密数据。  .NET Framework 开发员指南   加密数据  [C#]请参见
生成加密和解密的密钥 | 解密数据 | 加密任务 | 加密服务
语言
C#Visual Basic全部显示
执行对称加密和不对称加密时使用不同的过程。对流可以执行对称加密,因此对称加密对于加密大量的数据很有用。对少量字节执行不对称加密,因此不对称加密只对少量的数据有用。对称加密
托管对称加密类与称为 CryptoStream 的特殊流类(此特殊流类加密读入流中的数据)一起使用。CryptoStream 类使用以下参数进行初始化,它们是:一个托管流类,一个实现 ICryptoTransform 接口的类(它从实现加密算法的类创建,以及一个 CryptoStreamMode 枚举(它描述允许对 CryptoStream 进行的访问类型)。可以使用从 Stream 类派生的任何类(包括 FileStream、MemoryStream 和 NetworkStream)初始化 CryptoStream 类。使用这种方法,可以方便地对各种流对象执行对称加密。下面的示例阐释如何创建实现 Rijndael 加密算法的 RijndaelManaged 类的一个新实例,并使用该实例对 CryptoStream 类执行加密。在本示例中,使用称为 MyStream 的可以是任何托管流类型的流对象初始化 CryptoStream。将用于加密的密钥和 IV 传递给 RijndaelManaged 类的 CreateEncryptor 方法。这里使用了从 RMCrypto 生成的默认密钥和 IV。最后,传递 CryptoStreamMode.Write 以指定对流的写访问权。

解决方案 »

  1.   

    [C#]
    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.");
          }
       }
    }
      

  2.   

    这里有一个加密的例子:using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;namespace WindowsApplication1
    {
    /// <summary>
    /// Form1 的摘要说明。
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.OpenFileDialog openFileDialog1;
    private System.Windows.Forms.TextBox textBox1;
    private System.Windows.Forms.TextBox textBox2;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.TextBox textBox3;
    private System.Windows.Forms.Label label3;
    /// <summary>
    /// 必需的设计器变量。
    /// </summary>
    private System.ComponentModel.Container components = null; public Form1()
    {
    //
    // Windows 窗体设计器支持所必需的
    //
    InitializeComponent(); //
    // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
    //
    } /// <summary>
    /// 清理所有正在使用的资源。
    /// </summary>
    protected override void Dispose( bool disposing )
    {
    if( disposing )
    {
    if (components != null) 
    {
    components.Dispose();
    }
    }
    base.Dispose( disposing );
    } #region Windows Form Designer generated code
    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
    this.button1 = new System.Windows.Forms.Button();
    this.button2 = new System.Windows.Forms.Button();
    this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
    this.textBox1 = new System.Windows.Forms.TextBox();
    this.textBox2 = new System.Windows.Forms.TextBox();
    this.label1 = new System.Windows.Forms.Label();
    this.label2 = new System.Windows.Forms.Label();
    this.textBox3 = new System.Windows.Forms.TextBox();
    this.label3 = new System.Windows.Forms.Label();
    this.SuspendLayout();
    // 
    // button1
    // 
    this.button1.Location = new System.Drawing.Point(176, 200);
    this.button1.Name = "button1";
    this.button1.Size = new System.Drawing.Size(56, 24);
    this.button1.TabIndex = 0;
    this.button1.Text = "加密";
    this.button1.Click += new System.EventHandler(this.button1_Click);
    // 
    // button2
    // 
    this.button2.Location = new System.Drawing.Point(232, 200);
    this.button2.Name = "button2";
    this.button2.Size = new System.Drawing.Size(56, 24);
    this.button2.TabIndex = 1;
    this.button2.Text = "解密";
    this.button2.Click += new System.EventHandler(this.button2_Click);
    // 
    // textBox1
    // 
    this.textBox1.Location = new System.Drawing.Point(96, 48);
    this.textBox1.Name = "textBox1";
    this.textBox1.Size = new System.Drawing.Size(160, 21);
    this.textBox1.TabIndex = 4;
    this.textBox1.Text = "";
    // 
    // textBox2
    // 
    this.textBox2.Location = new System.Drawing.Point(96, 88);
    this.textBox2.Name = "textBox2";
    this.textBox2.Size = new System.Drawing.Size(160, 21);
    this.textBox2.TabIndex = 5;
    this.textBox2.Text = "";
    // 
    // label1
    // 
    this.label1.Location = new System.Drawing.Point(8, 48);
    this.label1.Name = "label1";
    this.label1.Size = new System.Drawing.Size(72, 24);
    this.label1.TabIndex = 6;
    this.label1.Text = "姓名";
    // 
    // label2
    // 
    this.label2.Location = new System.Drawing.Point(8, 88);
    this.label2.Name = "label2";
    this.label2.Size = new System.Drawing.Size(72, 24);
    this.label2.TabIndex = 7;
    this.label2.Text = "密码";
    this.label2.Click += new System.EventHandler(this.label2_Click);
    // 
    // textBox3
    // 
    this.textBox3.Location = new System.Drawing.Point(96, 120);
    this.textBox3.Name = "textBox3";
    this.textBox3.Size = new System.Drawing.Size(160, 21);
    this.textBox3.TabIndex = 8;
    this.textBox3.Text = "";
    // 
    // label3
    // 
    this.label3.Location = new System.Drawing.Point(8, 120);
    this.label3.Name = "label3";
    this.label3.Size = new System.Drawing.Size(72, 24);
    this.label3.TabIndex = 9;
    this.label3.Text = "配置信息";
    // 
    // Form1
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
    this.ClientSize = new System.Drawing.Size(292, 266);
    this.Controls.AddRange(new System.Windows.Forms.Control[] {
      this.label3,
      this.textBox3,
      this.label2,
      this.label1,
      this.textBox2,
      this.textBox1,
      this.button2,
      this.button1});
    this.Name = "Form1";
    this.Text = "Form1";
    this.ResumeLayout(false); }
    #endregion /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [STAThread]
    static void Main() 
    {
    Application.Run(new Form1());
    }
    private void button1_Click(object sender, System.EventArgs e)
    {

    FileStream fs  = new FileStream("EncryptedFile.dat",FileMode.Create,FileAccess.Write);
                    String clearText = this.textBox1.Text+Environment.NewLine+this.textBox2.Text+Environment.NewLine+this.textBox3.Text;
    Byte[] bytearray=Encoding.Unicode.GetBytes(clearText);

        byte[] Key=new Byte[]{1,3,5,7,9,11,13,15};
        byte[] IV=new Byte[]{0,2,4,6,8,10,12,14};
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    ICryptoTransform desencrypt = des.CreateEncryptor(Key,IV);

    CryptoStream cryptostream = new CryptoStream(fs,desencrypt,CryptoStreamMode.Write);
    cryptostream.Write(bytearray,0,bytearray.Length);
    cryptostream.Close();
    } private void label2_Click(object sender, System.EventArgs e)
    {

    } private void button2_Click(object sender, System.EventArgs e)
    {
    if (File.Exists("EncryptedFile.dat"))
    {
    FileStream fs  = new FileStream("EncryptedFile.dat",FileMode.Open,FileAccess.Read);
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    byte[] Key=new Byte[]{1,3,5,7,9,11,13,15};
    byte[] IV=new Byte[]{0,2,4,6,8,10,12,14};
    ICryptoTransform desdecrypt = des.CreateDecryptor(Key,IV);
    CryptoStream Decrstream = new CryptoStream(fs,desdecrypt,CryptoStreamMode.Read);
    StreamReader sr=new StreamReader(Decrstream,Encoding.Unicode);
                    

    this.textBox1.Text=sr.ReadLine();
    this.textBox2.Text=sr.ReadLine();
    this.textBox3.Text=sr.ReadLine();
    sr.Close();
    Decrstream.Close();

    }
    else
    MessageBox.Show("文件' EncryptedFile.dat '丢失");
    }
    }
    }