加密、解密

1、DES的加密解密的用法(可逆)

using System;
using System.Security.Cryptography;
using System.IO;

namespace DEMO
{
    
/// <summary>
    
/// CDESEncrypt 的摘要说明。使用标准64位DES加密
    
/// </summary>

    public class CDES
    
{
        
private byte[] FIV ;
        
private byte[] FKEY ;
        
public CDES()
        
{
            
// TODO: 在此处添加构造函数逻辑
            this.DefaultInit();
        }


        
/// <summary>
        
/// 默认键值和初始向量
        
/// </summary>

        private void DefaultInit()
        
{
            
byte[] IV = 155,1032468369923436 };
            
byte[] key =1421693156784218132 };
            FIV 
= IV;
            FKEY 
= key;
        }


        
/// <summary>
        
/// 采用标准 64位 DES 算法加密
        
/// </summary>
        
/// <param name="strText">要加密的字符串</param>
        
/// <returns>返回加密后的字符串</returns>

        public string Encrypt(string strText)
        
{
            DESCryptoServiceProvider des 
= new DESCryptoServiceProvider();
            MemoryStream ms 
= new MemoryStream();
            CryptoStream cs 
= new CryptoStream(ms,des.CreateEncryptor(FKEY,FIV),CryptoStreamMode.Write);
            StreamWriter sw 
= new StreamWriter(cs);
            sw.Write(strText);
            sw.Flush();
            cs.FlushFinalBlock();
            ms.Flush();
            
return Convert.ToBase64String(ms.GetBuffer(),0,Convert.ToInt32(ms.Length));
        }



        
/// <summary>
        
/// 标准64位DES解密
        
/// </summary>
        
/// <param name="strText">要解密的字符串</param>
        
/// <returns>返回解密后的字符串</returns>

        public string Decrypt(string strText)
        
{
            DESCryptoServiceProvider des 
= new DESCryptoServiceProvider();
            
byte[] inputByteArray = Convert.FromBase64String(strText);
            MemoryStream ms 
= new MemoryStream(inputByteArray);
            CryptoStream cs 
= new CryptoStream(ms,des.CreateDecryptor(FKEY, FIV),CryptoStreamMode.Read);
            StreamReader sr 
= new StreamReader(cs);
            
return sr.ReadToEnd();
        }


    }

}


调用方法范例:

            CDES YY = new CDES();
            
string t = "1234567";
            t 
= YY.Encrypt(t);
            MessageBox.Show(t);

            MessageBox.Show(YY.Decrypt(t));



2、SHA1加密的简单用法(不可逆)

例1:添加引用,选择System.Web.Dll
然后写

System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("password","sha1"); 


例2:
引入命名空间:

using System.Security.Cryptography;


编写下面静态方法:

        private static string HashString(string textToHash) 
        
{
            SHA1CryptoServiceProvider SHA1 
= new SHA1CryptoServiceProvider();
            
byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(textToHash);
            
byte[] byteHash = SHA1.ComputeHash(byteValue);
            SHA1.Clear();

            
return Convert.ToBase64String(byteHash);
        }

调用:

string passwordHash = HashString(txtPSW.ToStrong());

 

posted @ 2006-11-11 10:13  '.Elvis.'  阅读(161)  评论(0编辑  收藏  举报