当前位置:编程学习 > 网站相关 >>

加密与解密

using System; 
using System.Text; 
using System.IO; 
using System.Security.Cryptography; 
 
namespace Ming.Encrypt 

    public class EncryptLib 
    { 
        const string sou = "mingming"; 
        static byte[] rgbKey = null; 
        static byte[] rgbIV = null; 
        static EncryptLib() 
        { 
            rgbKey = Encoding.ASCII.GetBytes(sou); 
            rgbIV = rgbKey; 
        } 
 
        public static string Key 
        { 
            set { rgbKey = Encoding.ASCII.GetBytes(value); } 
        } 
 
        public static string IV 
        { 
            set { rgbIV = Encoding.ASCII.GetBytes(value); } 
        } 
 
        public static string Encode(string data) 
        { 
            MemoryStream ms = new MemoryStream(); 
            DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
            CryptoStream cst = new CryptoStream(ms, des.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); 
            StreamWriter sw = new StreamWriter(cst); 
            sw.WriteLine(data); 
            sw.Close(); 
            cst.Close(); 
            byte[] ret = ms.ToArray(); 
            ms.Close(); 
            return Convert.ToBase64String(ret); 
        } 
 
        public static string Decode(string data) 
        { 
            byte[] by = Convert.FromBase64String(data); 
            MemoryStream ms = new MemoryStream(by); 
            DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
            CryptoStream cst = new CryptoStream(ms, des.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Read); 
            StreamReader sr = new StreamReader(cst); 
            string ret = sr.ReadLine(); 
            sr.Close(); 
            cst.Close(); 
            ms.Close(); 
            return ret; 
        } 
 
        //MD5不可逆加密   //32位加密    
        public static string GetMD5_32(string s, string charset) 
        { 
            MD5 md5 = new MD5CryptoServiceProvider(); 
            byte[] t = md5.ComputeHash(Encoding.GetEncoding(charset).GetBytes(s)); 
            StringBuilder sb = new StringBuilder(32); 
            for (int i = 0; i < t.Length; i++) 
                sb.Append(t[i].ToString("x").PadLeft(2, '0')); 
            return sb.ToString(); 
        } 
 
        //MD5不可逆加密 //16位加密    
        public static string GetMd5_16(string ConvertString) 
        { 
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); 
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8); 
            t2 = t2.Replace("-", ""); 
            return t2; 
        } 
    } 

 


摘自 Ming

补充:综合编程 , 安全编程 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,