看这个例子,用RSA实现非对称加密和解密,
using System;
using System.Security.Cryptography;
using System.Text;class RSACSPSample
{ static void Main()
{
try
{
//Create a UnicodeEncoder to convert between byte array and string.
UnicodeEncoding ByteConverter = new UnicodeEncoding(); //Create byte arrays to hold original, encrypted, and decrypted data.
byte[] dataToEncrypt = ByteConverter.GetBytes("Data to Encrypt");
byte[] encryptedData;
byte[] decryptedData;
            
//Create a new instance of RSACryptoServiceProvider to generate
//public and private key data.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); //Pass the data to ENCRYPT, the public key information 
//(using RSACryptoServiceProvider.ExportParameters(false),
//and a boolean flag specifying no OAEP padding.
encryptedData = RSAEncrypt(dataToEncrypt,RSA.ExportParameters(false), false);
Console.WriteLine("encrypted plaintext: {0}", ByteConverter.GetString(encryptedData)); //Pass the data to DECRYPT, the private key information 
//(using RSACryptoServiceProvider.ExportParameters(true),
//and a boolean flag specifying no OAEP padding.
decryptedData = RSADecrypt(encryptedData,RSA.ExportParameters(true), false); //Display the decrypted plaintext to the console. 
Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData));
}
catch(ArgumentNullException)
{
//Catch this exception in case the encryption did
//not succeed.
Console.WriteLine("Encryption failed."); }
} static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
{
try
{    
//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); //Import the RSA Key information. This only needs
//toinclude the public key information.
RSA.ImportParameters(RSAKeyInfo); //Encrypt the passed byte array and specify OAEP padding.  
//OAEP padding is only available on Microsoft Windows XP or
//later.  
return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
}
//Catch and display a CryptographicException  
//to the console.
catch(CryptographicException e)
{
Console.WriteLine(e.Message); return null;
} } static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo,bool DoOAEPPadding)
{
try
{
//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); //Import the RSA Key information. This needs
//to include the private key information.
RSA.ImportParameters(RSAKeyInfo); //Decrypt the passed byte array and specify OAEP padding.  
//OAEP padding is only available on Microsoft Windows XP or
//later.  
return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}
//Catch and display a CryptographicException  
//to the console.
catch(CryptographicException e)
{
Console.WriteLine(e.ToString()); return null;
} }
}另见msdn文档和
下面网址
  http://www.zdnet.com.cn/developer/tech/story/0,2000081602,39109293,00.htm
  http://go.microsoft.com/fwlink/?linkid=3268&url=/quickstart/howto/doc/fileencrypt.aspx%20
  http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcryptographyoverview.asp?frame=true

解决方案 »

  1.   

    加密函数需要字节数组作为参数,因此,加密数据的第一步是把加密文本转换为字节数组。
    下面的例子使用了System.Text命名空间的UnicodeEncoding类。
    [Visual Basic .NET]
    Imports System.Text
    Imports System.Security.CryptographyDim UE As New UnicodeEncoding()
    Dim arInput As Byte() = UE.GetBytes(txtClear.Text)[C#]
    using System.Text;
    using System.Security.Cryptography;UnicodeEncoding UE = new UnicodeEncoding();
    byte[] arInput = UE.GetBytes(txtClear.Text);第二步是创建一个对称加密类的实例。创建对称加密类实例时创建了一个默认的密钥和IV,可以保存它们并在解密数据时使用。下面的示例把密钥和IV存储到会话变量中:
    [Visual Basic .NET]
    Dim des As New DESCryptoServiceProvider()
    Session("Key") = des.Key
    Session("IV") = des.IV[C#]
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    Session["Key"] = des.Key;
    Session["IV"] = des.IV;第三步是从对称加密对象中调用CreateEncryptor方法,创建一个加密器对象ICryptoTransform的实例。
    [Visual Basic .NET]
    Dim desEncrypt As ICryptoTransform = des.CreateEncryptor()[C#]
    ICryptoTransform desEncrypt = des.CreateEncryptor();执行对称加密的第四步是创建一个CryptoStream对象。
    公共语言运行库使用面向流的设计进行加密。流是一系列字节的抽象概念,例如文件、输入/输出设备、进程间通信管道或TCP/IP套接字。该设计的核心是CryptoStream对象。实现CryptoStream的任何加密对象可以和实现Stream的任何对象链接起来,因此一个对象的流式处理输出可以馈送到另一个对象的输入。对称加密是对流进行操作的。可以创建CryptoStream对象对读入流中的数据加密;可以传递一个Stream类和一个CryptoStreamMode枚举(它描述允许对CryptoStream进行的访问类型,Read表示解密,Write表示加密)创建CryptoStream对象;可以使用从Stream类派生的任何类(包括FileStream、MemoryStream和NetworkStream)初始化CryptoStream类。
    加密操作的输出可以是从Stream派生的任何对象。下面的例子中,加密数据被写入MemoryStream:
    [Visual Basic .NET]
    Dim ms As New MemoryStream()
    ms.SetLength(arInput.Length)
    Dim cStream As New CryptoStream(ms, desEncrypt, _
    CryptoStreamMode.Write)[C#]
    MemoryStream ms = new MemoryStream();
    ms.SetLength(arInput.Length);
    CryptoStream cStream = new CryptoStream(ms, desEncrypt, 
    CryptoStreamMode.Write);执行对称加密的第五步是调用CryptoStream的Write方法,传递数据以及作为字节数组应被加密的字节数。CryptoStream对象把加密数据写入输出流中。
    [Visual Basic .NET]
    cStream.Write(arInput, 0, arInput.Length)
    cStream.Close()[C#]
    cStream.Write(arInput, 0, arInput.Length);
    cStream.Close();最后一步是从MemoryStream对象中读取加密数据。
    [Visual Basic .NET]
    Dim arOutput As Byte()
    arOutput = ms.ToArray()[C#]
    byte[] arOutput;
    arOutput = ms.ToArray();
      

  2.   

    解密:
    (1) 解密数据
    除了创建解密器对象传递给CryptoStream对象以外,解密数据与加密数据是相似的。
    解密数据的第一步是创建一个对称加密类的实例。
    第二步是传递存储的密钥和IV调用CreateDecryptor方法,创建一个解密器对象ICryptoTransform的实例,如下面的例子所示:
    [Visual Basic .NET]
    Dim des As New DESCryptoServiceProvider()
    Dim desDecrypt As ICryptoTransform = des.CreateDecryptor _
    (Session("Key"), Session("IV"))[C#]
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    ICryptoTransform desDecrypt = des.CreateDecryptor(
    (byte[])Session["Key"], (byte[])Session["IV"]);第三步是创建一个基于流的对象保存加密数据。在下面的代码示例中,初始化MemoryStream对象,参数为包含加密数据的arOutput字节数组。
    [Visual Basic .NET]
    Dim ms As New MemoryStream(arOutput)[C#]
    MemoryStream ms = new MemoryStream(arOutput);第四步是创建CryptoStream对象解密基于流的对象中的数据,CryptoStreamMode设置为Read。下面的代码示例创建了一个CryptoStream对象来解密MemoryStream对象中的数据。
    [Visual Basic .NET]
    Dim cStream As New CryptoStream(ms, desDecrypt, _
    CryptoStreamMode.Read)[C#]
    CryptoStream cStream = new CryptoStream(ms, desDecrypt, 
    CryptoStreamMode.Read);
    最后,第五步是使用StreamReader从CryptoStream中读取解密数据。可以使用StreamReader对象的ReadToEnd方法从CryptoStream中读取解密数据并返回一个字符串。
    下面的示例从CryptoStream中读取数据到文本框,从而解密MemoryStream数据并在文本框中显示解密文本。
    [Visual Basic .NET]
    txtDecrypted.Text = New StreamReader(cStream, _
    New UnicodeEncoding()).ReadToEnd()
    cStream.Close()[C#]
    txtDecrypted.Text = new StreamReader(cStream, 
    new UnicodeEncoding()).ReadToEnd();
    cStream.Close();
      

  3.   

    上面这位兄弟针对 对称加密 作了较详细的解释
    关于c#中加密与解密,有一个专门的名字空间:System.Security.Cryptography,可以参考一下
    里面对各种加密解密方式都有相关的类
      

  4.   

    完整的加密解密数据的过程:
    1.加密:
    RSACryptoServiceProvider rsac = new RSACryptoServiceProvider();
    //字节缓冲区定为64(密钥为1024),最大长度为(rsac.KeySize/8 - 11)
    byte[] src = new byte[64];
    //Encrypt.cs是要加密的文件
    FileStream fs = new FileStream("Encrypt.cs", FileMode.Open, FileAccess.Read);
    //Result.txt存储的是加密之后的数据
    FileStream res = new FileStream("Result.txt", FileMode.Create, FileAccess.Write);
    int len;
    //加密
    while ((len = fs.Read(src, 0, 64)) > 0) {
    byte[] temp = new byte[len];
    Array.Copy(src, 0, temp, 0, len);
    temp = rsac.Encrypt(temp, false);
    res.Write(temp, 0, temp.Length);
    }
    fs.Close();
    res.Close();
    //存储密钥到文件,以便解密用。
    StreamWriter sw = new StreamWriter("RSA.key");
    sw.Write(rsac.ToXmlString(true));
    sw.Close();2.解密:
    RSACryptoServiceProvider rsac = new RSACryptoServiceProvider();
    //读密钥
    StreamReader sr = new StreamReader("RSA.key");
    String str = sr.ReadToEnd();
    sr.Close();
    rsac.FromXmlString(str);byte[] src = new byte[128];FileStream fs = new FileStream("Result.txt", FileMode.Open, FileAccess.Read);
    FileStream res = new FileStream("Encrypt.txt", FileMode.Create, FileAccess.Write);
    int len;
    //解密
    while ((len = fs.Read(src, 0, 128)) > 0) {
    byte[] temp = new byte[len];
    Array.Copy(src, 0, temp, 0, len);
    temp = rsac.Decrypt(temp, false);
    res.Write(temp, 0, temp.Length);
    }
    fs.Close();
    res.Close();