呵呵,为了mm??    先顶你一下.^_^能否说明白一点什么文件,文本,还是其他的什么,加密的方式是什么样的,你要(她要)控制台程序还是windows程序。虽然我不一定能写得出来,但是问清楚一点,或许对后面的大虾有帮助

解决方案 »

  1.   

    using System;
    using System.IO;
    using System.Text;
    using System.Collections;
    using System.Security.Cryptography;namespace Encryption
    {
    /// <summary>
    /// Summary description for Crptography.
    /// Uses TripleDES Symmetric alogorithm to encrypt and decyrpt streams.
    /// This algorithm uses a 24 byte key and a 8 byte initialization vector.
    /// </summary>
    public class Cryptography
    {
    //DES instance with random key
    private TripleDESCryptoServiceProvider des ; 
    private ICryptoTransform encrypt; //Encryptor
    private ICryptoTransform decrypt; // Decryptor public Cryptography()
    {
    des = new  TripleDESCryptoServiceProvider(); 
    string strKey = "this is a key for doing encryption"; // This is made a constant here. it can be mentioned in a config file also.
    byte[] key = Get24ByteKey(strKey);
    byte[] ivector = Get8ByteInitializationVector(strKey);

    //create DES Encryptor from this instance
    encrypt = des.CreateEncryptor(key,ivector); //create DES Decryptor from our des instance
    decrypt = des.CreateDecryptor(key,ivector); }
    public Stream Encrypt(Stream StreamtoEncrypt)
    {
    int len = (int) StreamtoEncrypt.Length; 
    byte[] bytearrayinput = new byte[len]; // Intermediate storage for Encryption
    int i = StreamtoEncrypt.Read(bytearrayinput,0,bytearrayinput.Length); //The encryptor takes bytearray as the input.So read the data from stream into bytearray

    byte[] bytearrayoutput = encrypt.TransformFinalBlock(bytearrayinput,0,bytearrayinput.Length);

    MemoryStream EncryptedStream = new MemoryStream();
    EncryptedStream.Write(bytearrayoutput,0,bytearrayoutput.Length); // Write the output into  a Stream to return a Stream
    EncryptedStream.Position = 0; // Set position to zero.

    return EncryptedStream; // Return the encryptedstream
    } public Stream Decrypt(Stream StreamtoDecrypt)
    {
    string StrtoDecrypt= new StreamReader(StreamtoDecrypt,new UnicodeEncoding()).ReadToEnd(); // The input stream here doesnot have length defined. So convert it to a StreamReader.
    byte[] bytearrayinput = new byte[4096];
    bytearrayinput =new UnicodeEncoding().GetBytes(StrtoDecrypt);  //The decryptor takes bytearray as the input.

    byte[] bytearrayoutput = decrypt.TransformFinalBlock(bytearrayinput,0,bytearrayinput.Length); 

    MemoryStream DecryptedStream = new MemoryStream();
    DecryptedStream.Write(bytearrayoutput,0,bytearrayoutput.Length); // Write the output into  a Stream to return a Stream
    DecryptedStream.Position= 0; // Set position to zero.

    return DecryptedStream; // Return the decryptedstream
    } private static byte[] Get24ByteKey(string phrase)
    {
    // Takes any string and returns a 24 byte array
    SHA256 sh = new SHA256Managed();
    byte[] hash = sh.ComputeHash(new UnicodeEncoding().GetBytes(phrase));
    byte[] retVal = new byte[24];
    for (int j=0; j < retVal.Length; j++) 
    {
    retVal.SetValue(hash.GetValue(j),j); }
    return retVal;
    } private static byte[] Get8ByteInitializationVector(string phrase)
    {
    // Takes any string and returns a 8 byte array
    SHA256 sh = new SHA256Managed();
    byte[] hash = sh.ComputeHash(new UnicodeEncoding().GetBytes(phrase));
    byte[] retVal = new byte[8];
    for (int j=0; j < retVal.Length; j++) 

    retVal.SetValue(hash.GetValue(j),j); 
    }
    return retVal;
    }
    }
    }
      

  2.   

    正如楼上所言,就用System.Security.Cryptography;命名空间的类,看看MSDN就知道了不是很难的,呵呵
      

  3.   

    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    //使用System.IO命名空间中的FileStream类进行文件io操作。
    using System.IO ;
    //使用System.Security.Cryptography命名空间中的DESCryptoServiceProvider类进行加密解密。
    using System.Security.Cryptography;
    namespace test
    {
    /// <summary>
    /// Form1 的摘要说明。
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Button button1;
    /// <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.SuspendLayout();
          // 
          // button1
          // 
          this.button1.Location = new System.Drawing.Point(64, 56);
          this.button1.Name = "button1";
          this.button1.TabIndex = 0;
          this.button1.Text = "button1";
          this.button1.Click += new System.EventHandler(this.button1_Click);
          // 
          // Form1
          // 
          this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
          this.ClientSize = new System.Drawing.Size(224, 166);
          this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                      this.button1});
          this.Name = "Form1";
          this.Text = "Form1";
          this.ResumeLayout(false);    }
    #endregion /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [STAThread]
    static void Main() 
    {
    Application.Run(new Form1());
    }    //加密函数myEndata,inName为输入文件,outName为输出文件,desKey为des加密算法的密钥,desIV为des算法的加密向量。密钥和向量要求是8位byte数组。因为私钥算法是对称算法,所以把CryptoStream类实例化语句中的des.CreateEncryptor改为des.CreateDecryptor即成为解密函数。
        private static void myEndata(String inName, String outName, byte[] desKey, byte[] desIV)
        {    
          //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.
     
          DES des = new DESCryptoServiceProvider();          
          CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);        
     
          //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();                   
        }    //解密函数myDedata,inName为输入文件,outName为输出文件,desKey为des加密算法的密钥,desIV为des算法的加密向量。密钥和向量要求是8位byte数组,必须和加密时一样。其实这个函数和加密函数只有CreateDecryptor和CreateEncryptor这一处不同。
        private static void myDedata(String inName, String outName, byte[] desKey, byte[] desIV)
        {    
          //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.
     
          DES des = new DESCryptoServiceProvider();          
          CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);        
     
          //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();                   
        }    
        //在button1的Click事件中调用加密函数,把in.txt加密,输出到out.txt,在把out.txt解密后输出到out2.txt.
        private void button1_Click(object sender, System.EventArgs e)
        {
          byte[] myDesKey={11,22,33,44,55,66,77,88};
          byte[] myDesIV={88,77,66,55,44,33,22,11};
          myEndata("c:\\in.txt","c:\\out.txt",myDesKey,myDesIV);
          myDedata("c:\\out.txt","c:\\out2.txt",myDesKey,myDesIV);  
        }
    }
    }
      

  4.   

    //名称空间  
    using  System;  
    using  System.Security.Cryptography;  
    using  System.IO;  
    using  System.Text;  
     
    //方法  
    //加密方法  
    public    string  Encrypt(string  pToEncrypt,  string  sKey)  
    {  
               DESCryptoServiceProvider  des  =  new  DESCryptoServiceProvider();  
               //把字符串放到byte数组中  
                     //原来使用的UTF8编码,我改成Unicode编码了,不行  
               byte[]  inputByteArray  =  Encoding.Default.GetBytes(pToEncrypt);  
               //byte[]  inputByteArray=Encoding.Unicode.GetBytes(pToEncrypt);  
     
               //建立加密对象的密钥和偏移量  
               //原文使用ASCIIEncoding.ASCII方法的GetBytes方法  
               //使得输入密码必须输入英文文本  
               des.Key  =  ASCIIEncoding.ASCII.GetBytes(sKey);  
               des.IV  =  ASCIIEncoding.ASCII.GetBytes(sKey);  
               MemoryStream  ms  =  new  MemoryStream();  
               CryptoStream  cs  =  new  CryptoStream(ms,  des.CreateEncryptor(),CryptoStreamMode.Write);  
               //Write  the  byte  array  into  the  crypto  stream  
               //(It  will  end  up  in  the  memory  stream)  
               cs.Write(inputByteArray,  0,  inputByteArray.Length);  
               cs.FlushFinalBlock();  
               //Get  the  data  back  from  the  memory  stream,  and  into  a  string  
               StringBuilder  ret  =  new  StringBuilder();  
               foreach(byte  b  in  ms.ToArray())  
                           {  
                           //Format  as  hex  
                           ret.AppendFormat("{0:X2}",  b);  
                           }  
               ret.ToString();  
               return  ret.ToString();  
    }  
     
    //解密方法  
    public    string  Decrypt(string  pToDecrypt,  string  sKey)  
    {  
               DESCryptoServiceProvider  des  =  new  DESCryptoServiceProvider();  
     
               //Put  the  input  string  into  the  byte  array  
               byte[]  inputByteArray  =  new  byte[pToDecrypt.Length  /  2];  
               for(int  x  =  0;  x  <  pToDecrypt.Length  /  2;  x++)  
               {  
                         int  i  =  (Convert.ToInt32(pToDecrypt.Substring(x  *  2,  2),  16));  
                   inputByteArray[x]  =  (byte)i;  
               }  
     
               //建立加密对象的密钥和偏移量,此值重要,不能修改  
               des.Key  =  ASCIIEncoding.ASCII.GetBytes(sKey);  
               des.IV  =  ASCIIEncoding.ASCII.GetBytes(sKey);  
               MemoryStream  ms  =  new  MemoryStream();  
               CryptoStream  cs  =  new  CryptoStream(ms,  des.CreateDecryptor(),CryptoStreamMode.Write);  
               //Flush  the  data  through  the  crypto  stream  into  the  memory  stream  
               cs.Write(inputByteArray,  0,  inputByteArray.Length);  
               cs.FlushFinalBlock();  
     
               //Get  the  decrypted  data  back  from  the  memory  stream  
               //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象  
               StringBuilder  ret  =  new  StringBuilder();  
                 
               return  System.Text.Encoding.Default.GetString(ms.ToArray());  
    }  
     
    //-------代码完毕--------------------  
     
    注意:sKey输入密码的时候,必须使用英文字符,区分大小写,且字符数量是8个,不能多也不能少,否则出错。  
      

  5.   

    谢谢上面的各位大侠。谢谢!我还有个过分的问题,就是怎么把上面的代码放到项目里呀?我新创建了一个项目,把代码copy进去,有错。由于我一点也不会C# ,所以还请大侠指点。或者那位大哥大姐直接给我一个完整的项目文件吧。
      我又开了一个新贴,上面的各位只要去了就给分。
      http://expert.csdn.net/Expert/topic/1870/1870019.xml?temp=6.286258E-02