.NET中的加密解密:私钥加密(对称加密):DES

 

    public class DesSample
    {
        DES des 
= null;

        
public DesSample(byte[] bKey)
        {
            des 
= new DESCryptoServiceProvider();
            des.Key 
= bKey;
            des.IV 
= bKey;
        }

        
public string Encrypt(string data)
        {
            
try
            {
                
byte[] bData = Encoding.UTF8.GetBytes(data);
                MemoryStream ms 
= new MemoryStream();
                CryptoStream cs 
= new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(bData, 
0, bData.Length);
                cs.FlushFinalBlock();

                
return Convert.ToBase64String(ms.ToArray());
            }
            
catch
            {
                
throw;
            }
        }

        
public string Decrypt(string data)
        {
            
try
            {
                
byte[] bData = Convert.FromBase64String(data);
                MemoryStream ms 
= new MemoryStream();
                CryptoStream cs 
= new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(bData, 
0, bData.Length);
                cs.FlushFinalBlock();

                
return Encoding.UTF8.GetString(ms.ToArray());
            }
            
catch
            {
                
throw;
            }
        }

    }
//class DesSample


    
class Program
    {
        
static void Main(string[] args)
        {
            
            
byte[] bKey8 = UTF8Encoding.UTF8.GetBytes("12345678");
            
string data = "Hello,I am Jie.";

            Console.WriteLine(
"Des Sample");
            DesSample des 
= new DesSample(bKey8);
            
string desData = "";
            desData 
= des.Encrypt(data);
            Console.WriteLine(
"DES Encrypt:{0}", desData);
            Console.WriteLine(
"DES Decrypt:{0}", des.Decrypt(desData));
            Console.WriteLine();

            Console.Read();
        }
    }

 

 

posted @ 2010-03-09 14:40  xyj  阅读(347)  评论(0编辑  收藏  举报