.net加密解密学习总结

280 篇文章 6 订阅
106 篇文章 2 订阅

.NET中的DES加密解密

http://blog.csdn.net/pan_junbiao/article/details/7032700

  System.Security.Cryptography名字空间包含了实现安全方案的类,例如加密和解密数据、管理密

钥、验证数据的完整性并确保数据没有被篡改等等。
  加密和解密的算法分为对称(symmetric)算法和不对称(asymmetric)算法。对称算法在加密和解

密数据时使用相同的密钥和初始化矢量,典型的有DES、 TripleDES和Rijndael算法,它适用于不需要传

递密钥的情况,主要用于本地文档或数据的加密。不对称算法有两个不同的密钥,分别是公共密钥和私

有密钥,公共密钥在网络中传递,用于加密数据,而私有密钥用于解密数据。不对称算法主要有RSA、

DSA等,主要用于网络数据的加密。

加密和解密本地文档

下面的例子是.NET中加密和解密本地文本,使用的是DES对称算法。
1、引用文件

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

2、编写DES加密/解密方法

public static string _KEY = "HQDCKEY1";  //密钥  
public static string _IV = "HQDCKEY2";   //向量  
  
/// <summary>  
/// 加密  
/// </summary>  
/// <param name="data"></param>  
/// <returns></returns>  
public static string Encode(string data)  
{  
  
    byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_KEY);  
    byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(_IV);  
  
    DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();  
    int i = cryptoProvider.KeySize;  
    MemoryStream ms = new MemoryStream();  
    CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), 
CryptoStreamMode.Write);  
  
    StreamWriter sw = new StreamWriter(cst);  
    sw.Write(data);  
    sw.Flush();  
    cst.FlushFinalBlock();  
    sw.Flush();  
  
    string strRet = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);  
    return strRet;  
}  
  
/// <summary>  
/// 解密  
/// </summary>  
/// <param name="data"></param>  
/// <returns></returns>  
public static string Decode(string data)  
{  
  
    byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_KEY);  
    byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(_IV);  
  
    byte[] byEnc;  
  
    try  
    {  
        data.Replace("_%_", "/");  
        data.Replace("-%-", "#");  
        byEnc = Convert.FromBase64String(data);  
    }  
    catch  
    {  
        return null;  
    }  
  
    DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();  
    MemoryStream ms = new MemoryStream(byEnc);  
    CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), 

CryptoStreamMode.Read);  
    StreamReader sr = new StreamReader(cst);  
    return sr.ReadToEnd();  
}


  

3、运行测试

static void Main(string[] args)  
{  
    string data = "http://blog.csdn.net/pan_junbiao/";  //要加密的数据  
    string encodeStr = "";   //加密后文本  
    string decodeStr = "";   //解密后文本  
  
    Console.WriteLine("原文本:{0}", data);  
    encodeStr = Encode(data);  
    Console.WriteLine("加密后文本:{0}", encodeStr);  
    decodeStr = Decode(encodeStr);  
    Console.WriteLine("解密后文本:{0}", decodeStr);  
    Console.Read();  
} 


========

.net常用加密解密方法

http://www.cnblogs.com/qinweilong/archive/2010/06/30/1768535.html
 

private byte[] _power;
/// <summary>
        /// 用户权限
        /// </summary>
        public byte[] Power
        {
            set { _power = value; }
            get { return _power; }
        }
sql:
Power binary  4000
解密:
Encoding.Unicode.GetString(model.Power);
加密:
byte[] Power = new UnicodeEncoding().GetBytes(this.HidPowers.Value);
                model.Power = Power;


using System;
using System.Security.Cryptography;  
using System.Text;
namespace BeidouWY.Common.DEncrypt
{
    /// <summary>
    /// Encrypt 的摘要说明。
    /// LiTianPing
    /// </summary>
    public class DEncrypt
    {
        /// <summary>
        /// 构造方法
        /// </summary>
        public DEncrypt()  
        {  
        } 

        #region 使用 缺省密钥字符串 加密/解密string

        /// <summary>
        /// 使用缺省密钥字符串加密string
        /// </summary>
        /// <param name="original">明文</param>
        /// <returns>密文</returns>
        public static string Encrypt(string original)
        {
            return Encrypt(original,"MATICSOFT");
        }
        /// <summary>
        /// 使用缺省密钥字符串解密string
        /// </summary>
        /// <param name="original">密文</param>
        /// <returns>明文</returns>
        public static string Decrypt(string original)
        {
            return Decrypt(original,"MATICSOFT",System.Text.Encoding.Default);
        }

        #endregion

        #region 使用 给定密钥字符串 加密/解密string
        /// <summary>
        /// 使用给定密钥字符串加密string
        /// </summary>
        /// <param name="original">原始文字</param>
        /// <param name="key">密钥</param>
        /// <param name="encoding">字符编码方案</param>
        /// <returns>密文</returns>
        public static string Encrypt(string original, string key)  
        {  
            byte[] buff = System.Text.Encoding.Default.GetBytes(original);  
            byte[] kb = System.Text.Encoding.Default.GetBytes(key);
            return Convert.ToBase64String(Encrypt(buff,kb));      
        }
        /// <summary>
        /// 使用给定密钥字符串解密string
        /// </summary>
        /// <param name="original">密文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public static string Decrypt(string original, string key)
        {
            return Decrypt(original,key,System.Text.Encoding.Default);
        }

        /// <summary>
        /// 使用给定密钥字符串解密string,返回指定编码方式明文
        /// </summary>
        /// <param name="encrypted">密文</param>
        /// <param name="key">密钥</param>
        /// <param name="encoding">字符编码方案</param>
        /// <returns>明文</returns>
        public static string Decrypt(string encrypted, string key,Encoding encoding)  
        {       
            byte[] buff = Convert.FromBase64String(encrypted);  
            byte[] kb = System.Text.Encoding.Default.GetBytes(key);
            return encoding.GetString(Decrypt(buff,kb));      
        }  
        #endregion

        #region 使用 缺省密钥字符串 加密/解密/byte[]
        /// <summary>
        /// 使用缺省密钥字符串解密byte[]
        /// </summary>
        /// <param name="encrypted">密文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public static byte[] Decrypt(byte[] encrypted)  
        {  
            byte[] key = System.Text.Encoding.Default.GetBytes("MATICSOFT"); 
            return Decrypt(encrypted,key);     
        }
        /// <summary>
        /// 使用缺省密钥字符串加密
        /// </summary>
        /// <param name="original">原始数据</param>
        /// <param name="key">密钥</param>
        /// <returns>密文</returns>
        public static byte[] Encrypt(byte[] original)  
        {  
            byte[] key = System.Text.Encoding.Default.GetBytes("MATICSOFT"); 
            return Encrypt(original,key);     
        }  
        #endregion

        #region  使用 给定密钥 加密/解密/byte[]

        /// <summary>
        /// 生成MD5摘要
        /// </summary>
        /// <param name="original">数据源</param>
        /// <returns>摘要</returns>
        public static byte[] MakeMD5(byte[] original)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();   
            byte[] keyhash = hashmd5.ComputeHash(original);       
            hashmd5 = null;  
            return keyhash;
        }

        /// <summary>
        /// 使用给定密钥加密
        /// </summary>
        /// <param name="original">明文</param>
        /// <param name="key">密钥</param>
        /// <returns>密文</returns>
        public static byte[] Encrypt(byte[] original, byte[] key)  
        {  

            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();      

 

            des.Key =  MakeMD5(key);
            des.Mode = CipherMode.ECB;  
     
            return des.CreateEncryptor().TransformFinalBlock(original, 0, original.Length);     
        }  

        /// <summary>
        /// 使用给定密钥解密数据
        /// </summary>
        /// <param name="encrypted">密文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public static byte[] Decrypt(byte[] encrypted, byte[] key)  
        {  
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();  
            des.Key =  MakeMD5(key);    
            des.Mode = CipherMode.ECB;  

            return des.CreateDecryptor().TransformFinalBlock(encrypted, 0, encrypted.Length);
        }  
  
        #endregion    
    }
}

using System;
using System.Security.Cryptography;  
using System.Text;
namespace BeidouWY.Common.DEncrypt
{
    /// <summary>
    /// DES加密/解密类。
    /// LiTianPing
    /// </summary>
    public class DESEncrypt
    {
        public DESEncrypt()
        {            
        }

        #region ========加密========  
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Encrypt(string Text) 
        {
            return Encrypt(Text,"MATICSOFT");
        }
        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Encrypt(string Text,string sKey) 
        { 
            DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
            byte[] inputByteArray; 
            inputByteArray=Encoding.Default.GetBytes(Text); 
            des.Key = ASCIIEncoding.ASCII.GetBytes

(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, 

"md5").Substring(0, 8)); 
            des.IV = ASCIIEncoding.ASCII.GetBytes


(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, 

"md5").Substring(0, 8)); 
            System.IO.MemoryStream ms=new System.IO.MemoryStream(); 
            CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor

(),CryptoStreamMode.Write); 
            cs.Write(inputByteArray,0,inputByteArray.Length); 
            cs.FlushFinalBlock(); 
            StringBuilder ret=new StringBuilder(); 
            foreach( byte b in ms.ToArray()) 
            { 
                ret.AppendFormat("{0:X2}",b); 
            } 
            return ret.ToString(); 
        } 

        #endregion
        
        #region ========解密========    
 
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Decrypt(string Text) 
        {
            return Decrypt(Text,"MATICSOFT");
        }
        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Decrypt(string Text,string sKey) 
        { 
            DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
            int len; 
            len=Text.Length/2; 
            byte[] inputByteArray = new byte[len]; 
            int x,i; 
            for(x=0;x<len;x++) 
            { 
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); 
                inputByteArray[x]=(byte)i; 
            } 
            des.Key = ASCIIEncoding.ASCII.GetBytes


(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, 


"md5").Substring(0, 8)); 
            des.IV = ASCIIEncoding.ASCII.GetBytes


(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, 


"md5").Substring(0, 8)); 
            System.IO.MemoryStream ms=new System.IO.MemoryStream(); 
            CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor


(),CryptoStreamMode.Write); 
            cs.Write(inputByteArray,0,inputByteArray.Length); 
            cs.FlushFinalBlock(); 
            return Encoding.Default.GetString(ms.ToArray()); 
        } 
 

        #endregion 

    }

}


using System;
using System.Text;
using System.Security.Cryptography;
namespace BeidouWY.Common.DEncrypt
{
    /// <summary>
    /// 得到随机安全码(哈希加密)。
    /// </summary>
    public class HashEncode
    {
        public HashEncode()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        /// <summary>
        /// 得到随机哈希加密字符串
        /// </summary>
        /// <returns></returns>
        public static string GetSecurity()
        {            
            string Security = HashEncoding(GetRandomValue());        
            return Security;
        }
        /// <summary>
        /// 得到一个随机数值
        /// </summary>
        /// <returns></returns>
        public static string GetRandomValue()
        {            
            Random Seed = new Random();
            string RandomVaule = Seed.Next(1, int.MaxValue).ToString();
            return RandomVaule;
        }
        /// <summary>
        /// 哈希加密一个字符串
        /// </summary>
        /// <param name="Security"></param>
        /// <returns></returns>
        public static string HashEncoding(string Security)
        {                        
            byte[] Value;
            UnicodeEncoding Code = new UnicodeEncoding();
            byte[] Message = Code.GetBytes(Security);
            SHA512Managed Arithmetic = new SHA512Managed();
            Value = Arithmetic.ComputeHash(Message);
            Security = "";
            foreach(byte o in Value)
            {
                Security += (int) o + "O";
            }
            return Security;
        }
    }
}


using System;
using System.Security;
using System.Security.Cryptography;
using System.Text;

namespace BeidouWY.Common.DEncrypt
{
    /// <summary>
    /// MD5Helper 的摘要说明。
    /// </summary>
    public class MD5Helper
    {
        /// <summary>
        /// 得到一个加密的字符串
        /// </summary>
        /// <param name="strIn">原始字符串</param>
        /// <returns>加密后字符串</returns>
        public static string GetMD5String(string strIn)
        {
            byte[] b=Encoding.Default.GetBytes(strIn);
            
            b=new MD5CryptoServiceProvider().ComputeHash(b);
            string strOut="";
            for(int i=0;i<b.Length;i++)
            {
                strOut+=b[i].ToString("x").PadLeft(2,'2');
            }
            return strOut;
        }
    }
}


using System; 
using System.Text; 
using System.Security.Cryptography; 
namespace BeidouWY.Common.DEncrypt

    /// <summary> 
    /// RSA加密解密及RSA签名和验证
    /// </summary> 
    public class RSACryption 
    {         
        public RSACryption() 
        {             
        } 
        


        #region RSA 加密解密 


        #region RSA 的密钥产生 
    
        /// <summary>
        /// RSA 的密钥产生 产生私钥 和公钥 
        /// </summary>
        /// <param name="xmlKeys"></param>
        /// <param name="xmlPublicKey"></param>
        public void RSAKey(out string xmlKeys,out string xmlPublicKey) 
        {             
                System.Security.Cryptography.RSACryptoServiceProvider rsa=new 


RSACryptoServiceProvider(); 
                xmlKeys=rsa.ToXmlString(true); 
                xmlPublicKey = rsa.ToXmlString(false);             
        } 
        #endregion 


        #region RSA的加密函数 
        //############################################################################## 
        //RSA 方式加密 
        //说明KEY必须是XML的行式,返回的是字符串 
        //在有一点需要说明!!该加密方式有 长度 限制的!! 
        //############################################################################## 


        //RSA的加密函数  string
        public string RSAEncrypt(string xmlPublicKey,string m_strEncryptString ) 
        { 
            
            byte[] PlainTextBArray; 
            byte[] CypherTextBArray; 
            string Result; 
            RSACryptoServiceProvider rsa=new RSACryptoServiceProvider(); 
            rsa.FromXmlString(xmlPublicKey); 
            PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString); 
            CypherTextBArray = rsa.Encrypt(PlainTextBArray, false); 
            Result=Convert.ToBase64String(CypherTextBArray); 
            return Result; 
            
        } 
        //RSA的加密函数 byte[]
        public string RSAEncrypt(string xmlPublicKey,byte[] EncryptString ) 
        { 
            
            byte[] CypherTextBArray; 
            string Result; 
            RSACryptoServiceProvider rsa=new RSACryptoServiceProvider(); 
            rsa.FromXmlString(xmlPublicKey); 
            CypherTextBArray = rsa.Encrypt(EncryptString, false); 
            Result=Convert.ToBase64String(CypherTextBArray); 
            return Result; 
            
        } 
        #endregion 


        #region RSA的解密函数 
        //RSA的解密函数  string
        public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString ) 
        {            
            byte[] PlainTextBArray; 
            byte[] DypherTextBArray; 
            string Result; 
            System.Security.Cryptography.RSACryptoServiceProvider rsa=new 


RSACryptoServiceProvider(); 
            rsa.FromXmlString(xmlPrivateKey); 
            PlainTextBArray =Convert.FromBase64String(m_strDecryptString); 
            DypherTextBArray=rsa.Decrypt(PlainTextBArray, false); 
            Result=(new UnicodeEncoding()).GetString(DypherTextBArray); 
            return Result; 
            
        } 


        //RSA的解密函数  byte
        public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString ) 
        {            
            byte[] DypherTextBArray; 
            string Result; 
            System.Security.Cryptography.RSACryptoServiceProvider rsa=new 


RSACryptoServiceProvider(); 
            rsa.FromXmlString(xmlPrivateKey); 
            DypherTextBArray=rsa.Decrypt(DecryptString, false); 
            Result=(new UnicodeEncoding()).GetString(DypherTextBArray); 
            return Result; 
            
        } 
        #endregion 


        #endregion 


        #region RSA数字签名 

        #region 获取Hash描述表 
        //获取Hash描述表 
        public bool GetHash(string m_strSource, ref byte[] HashData) 
        {             
            //从字符串中取得Hash描述 
            byte[] Buffer; 
            System.Security.Cryptography.HashAlgorithm MD5 = 


System.Security.Cryptography.HashAlgorithm.Create("MD5"); 
            Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource); 
            HashData = MD5.ComputeHash(Buffer); 


            return true;             
        } 


        //获取Hash描述表 
        public bool GetHash(string m_strSource, ref string strHashData) 
        { 
            
            //从字符串中取得Hash描述 
            byte[] Buffer; 
            byte[] HashData; 
            System.Security.Cryptography.HashAlgorithm MD5 = 


System.Security.Cryptography.HashAlgorithm.Create("MD5"); 
            Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource); 
            HashData = MD5.ComputeHash(Buffer); 


            strHashData = Convert.ToBase64String(HashData); 
            return true; 
            
        } 


        //获取Hash描述表 
        public bool GetHash(System.IO.FileStream objFile, ref byte[] HashData) 
        { 
            
            //从文件中取得Hash描述 
            System.Security.Cryptography.HashAlgorithm MD5 = 


System.Security.Cryptography.HashAlgorithm.Create("MD5"); 
            HashData = MD5.ComputeHash(objFile); 
            objFile.Close(); 


            return true; 
            
        } 


        //获取Hash描述表 
        public bool GetHash(System.IO.FileStream objFile, ref string strHashData) 
        { 
            
            //从文件中取得Hash描述 
            byte[] HashData; 
            System.Security.Cryptography.HashAlgorithm MD5 = 


System.Security.Cryptography.HashAlgorithm.Create("MD5"); 
            HashData = MD5.ComputeHash(objFile); 
            objFile.Close(); 


            strHashData = Convert.ToBase64String(HashData); 


            return true; 
            
        } 
        #endregion 


        #region RSA签名 
        //RSA签名 
        public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, 


ref byte[] EncryptedSignatureData) 
        { 
            
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new 


System.Security.Cryptography.RSACryptoServiceProvider(); 


                RSA.FromXmlString(p_strKeyPrivate); 
                System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new 


System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); 
                //设置签名的算法为MD5 
                RSAFormatter.SetHashAlgorithm("MD5"); 
                //执行签名 
                EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); 


                return true; 
            
        } 


        //RSA签名 
        public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, 


ref string m_strEncryptedSignatureData) 
        { 
            
                byte[] EncryptedSignatureData; 


                System.Security.Cryptography.RSACryptoServiceProvider RSA = new 


System.Security.Cryptography.RSACryptoServiceProvider(); 


                RSA.FromXmlString(p_strKeyPrivate); 
                System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new 


System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); 
                //设置签名的算法为MD5 
                RSAFormatter.SetHashAlgorithm("MD5"); 
                //执行签名 
                EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); 


                m_strEncryptedSignatureData = Convert.ToBase64String


(EncryptedSignatureData); 


                return true; 
            
        } 


        //RSA签名 
        public bool SignatureFormatter(string p_strKeyPrivate, string 


m_strHashbyteSignature, ref byte[] EncryptedSignatureData) 
        { 
            
                byte[] HashbyteSignature; 


                HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature); 
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new 


System.Security.Cryptography.RSACryptoServiceProvider(); 


                RSA.FromXmlString(p_strKeyPrivate); 
                System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new 


System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); 
                //设置签名的算法为MD5 
                RSAFormatter.SetHashAlgorithm("MD5"); 
                //执行签名 
                EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); 


                return true; 
            
        } 


        //RSA签名 
        public bool SignatureFormatter(string p_strKeyPrivate, string 


m_strHashbyteSignature, ref string m_strEncryptedSignatureData) 
        { 
            
                byte[] HashbyteSignature; 
                byte[] EncryptedSignatureData; 


                HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature); 
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new 


System.Security.Cryptography.RSACryptoServiceProvider(); 


                RSA.FromXmlString(p_strKeyPrivate); 
                System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new 


System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); 
                //设置签名的算法为MD5 
                RSAFormatter.SetHashAlgorithm("MD5"); 
                //执行签名 
                EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); 


                m_strEncryptedSignatureData = Convert.ToBase64String


(EncryptedSignatureData); 


                return true; 
            
        } 
        #endregion 


        #region RSA 签名验证 


        public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, 


byte[] DeformatterData) 
        { 
            
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new 


System.Security.Cryptography.RSACryptoServiceProvider(); 


                RSA.FromXmlString(p_strKeyPublic); 
                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = 


new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); 
                //指定解密的时候HASH算法为MD5 
                RSADeformatter.SetHashAlgorithm("MD5"); 


                if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData)) 
                { 
                    return true; 
                } 
                else 
                { 
                    return false; 
                } 
            
        } 


        public bool SignatureDeformatter(string p_strKeyPublic, string 


p_strHashbyteDeformatter, byte[] DeformatterData) 
        { 
            
                byte[] HashbyteDeformatter; 


                HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter); 


                System.Security.Cryptography.RSACryptoServiceProvider RSA = new 


System.Security.Cryptography.RSACryptoServiceProvider(); 


                RSA.FromXmlString(p_strKeyPublic); 
                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = 


new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); 
                //指定解密的时候HASH算法为MD5 
                RSADeformatter.SetHashAlgorithm("MD5"); 


                if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData)) 
                { 
                    return true; 
                } 
                else 
                { 
                    return false; 
                } 
            
        } 


        public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, 


string p_strDeformatterData) 
        { 
            
                byte[] DeformatterData; 


                System.Security.Cryptography.RSACryptoServiceProvider RSA = new 


System.Security.Cryptography.RSACryptoServiceProvider(); 


                RSA.FromXmlString(p_strKeyPublic); 
                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = 


new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); 
                //指定解密的时候HASH算法为MD5 
                RSADeformatter.SetHashAlgorithm("MD5"); 


                DeformatterData =Convert.FromBase64String(p_strDeformatterData); 


                if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData)) 
                { 
                    return true; 
                } 
                else 
                { 
                    return false; 
                } 
            
        } 


        public bool SignatureDeformatter(string p_strKeyPublic, string 


p_strHashbyteDeformatter, string p_strDeformatterData) 
        { 
            
                byte[] DeformatterData; 
                byte[] HashbyteDeformatter; 


                HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter); 
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new 


System.Security.Cryptography.RSACryptoServiceProvider(); 


                RSA.FromXmlString(p_strKeyPublic); 
                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = 


new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); 
                //指定解密的时候HASH算法为MD5 
                RSADeformatter.SetHashAlgorithm("MD5"); 


                DeformatterData =Convert.FromBase64String(p_strDeformatterData); 


                if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData)) 
                { 
                    return true; 
                } 
                else 
                { 
                    return false; 
                } 
            
        } 




        #endregion 




        #endregion 


    } 

========

Asp.Net 加密解密



#region DES加密解密
        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="strSource">待加密字串</param>
        /// <param name="key">32位Key值</param>
        /// <returns>加密后的字符串</returns>
        public string DESEncrypt(string strSource)
        {
            return DESEncrypt(strSource, DESKey);
        }
        public string DESEncrypt(string strSource, byte[] key)
        {
            SymmetricAlgorithm sa = Rijndael.Create();
            sa.Key = key;
            sa.Mode = CipherMode.ECB;
            sa.Padding = PaddingMode.Zeros;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, sa.CreateEncryptor(), 


CryptoStreamMode.Write);
            byte[] byt = Encoding.Unicode.GetBytes(strSource);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Convert.ToBase64String(ms.ToArray());
        }
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="strSource">待解密的字串</param>
        /// <param name="key">32位Key值</param>
        /// <returns>解密后的字符串</returns>
        public string DESDecrypt(string strSource)
        {
            return DESDecrypt(strSource, DESKey);
        }
        public string DESDecrypt(string strSource, byte[] key)
        {
            SymmetricAlgorithm sa = Rijndael.Create();
            sa.Key = key;
            sa.Mode = CipherMode.ECB;
            sa.Padding = PaddingMode.Zeros;
            ICryptoTransform ct = sa.CreateDecryptor();
            byte[] byt = Convert.FromBase64String(strSource);
            MemoryStream ms = new MemoryStream(byt);
            CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs, Encoding.Unicode);
            return sr.ReadToEnd();
        }
        #endregion


        #region 一个用hash实现的加密解密方法
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        public static string EncryptStrByHash(string src)
        {
            if (src.Length == 0)
            {
                return "";
            }
            byte[] HaKey = System.Text.Encoding.ASCII.GetBytes((src + "Test").ToCharArray


());
            byte[] HaData = new byte[20];
            HMACSHA1 Hmac = new HMACSHA1(HaKey);
            CryptoStream cs = new CryptoStream(Stream.Null, Hmac, CryptoStreamMode.Write);
            try
            {
                cs.Write(HaData, 0, HaData.Length);
            }
            finally
            {
                cs.Close();
            }
            string HaResult = System.Convert.ToBase64String(Hmac.Hash).Substring(0, 16);
            byte[] RiKey = System.Text.Encoding.ASCII.GetBytes(HaResult.ToCharArray());
            byte[] RiDataBuf = System.Text.Encoding.ASCII.GetBytes(src.ToCharArray());
            byte[] EncodedBytes =   { };
            MemoryStream ms = new MemoryStream();
            RijndaelManaged rv = new RijndaelManaged();
            cs = new CryptoStream(ms, rv.CreateEncryptor(RiKey, RiKey), 


CryptoStreamMode.Write);
            try
            {
                cs.Write(RiDataBuf, 0, RiDataBuf.Length);
                cs.FlushFinalBlock();
                EncodedBytes = ms.ToArray();
            }
            finally
            {
                ms.Close();
                cs.Close();
            }
            return HaResult + System.Convert.ToBase64String(EncodedBytes);
        }


        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        public static string DecrypStrByHash(string src)
        {
            if (src.Length < 40) return "";
            byte[] SrcBytes = System.Convert.FromBase64String(src.Substring(16));
            byte[] RiKey = System.Text.Encoding.ASCII.GetBytes(src.Substring(0, 


16).ToCharArray());
            byte[] InitialText = new byte[SrcBytes.Length];
            RijndaelManaged rv = new RijndaelManaged();
            MemoryStream ms = new MemoryStream(SrcBytes);
            CryptoStream cs = new CryptoStream(ms, rv.CreateDecryptor(RiKey, RiKey), 


CryptoStreamMode.Read);
            try
            {
                cs.Read(InitialText, 0, InitialText.Length);
            }
            finally
            {
                ms.Close();
                cs.Close();
            }
            System.Text.StringBuilder Result = new System.Text.StringBuilder();
            for (int i = 0; i < InitialText.Length; ++i) if (InitialText[i] > 0) 


Result.Append((char)InitialText[i]);
            return Result.ToString();
        }


        /// <summary>
        /// 对加密后的密文重新编码,如果密文长>16,则去掉前16个字符,如果长度小于16,返回空字符



        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public string ReEncryptStrByHash(string s)
        {
            string e = Encrypt.EncryptStrByHash(s);
            return ((e.Length > 16) ? e.Substring(16) : "");
        }
        #endregion


        #region Md5加密,生成16位或32位,生成的密文都是大写
        public static string Md5To16(string str)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash


(UTF8Encoding.Default.GetBytes(str)), 4, 8);
            t2 = t2.Replace("-", "");
            return t2;
        }


        <summary>
        /// MD5 32位加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Md5To32(string str)
        {
            string pwd = "";
            MD5 md5 = MD5.Create();
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
            for (int i = 0; i < s.Length; i++)
            {
                pwd = pwd + s[i].ToString("X");
            }
            return pwd;
        }
        #endregion


        #region 3DES加密解密
        public string Encrypt3DES(string str)
        {
            //密钥
            string sKey = "wyw308";
            //    //矢量,可为空
            string sIV = "scf521";
            //    //构造对称算法
            SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();


            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            mCSP.Key = Convert.FromBase64String(sKey);
            mCSP.IV = Convert.FromBase64String(sIV);
            mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
            mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
            byt = Encoding.UTF8.GetBytes(str);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Convert.ToBase64String(ms.ToArray());
        }
        /// <summary>
        /// 带指定密钥和矢量的3DES加密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="sKey"></param>
        /// <param name="sIV"></param>
        /// <returns></returns>
        public string Encrypt3DES(string str, string sKey, string sIV)
        {
            SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            mCSP.Key = Convert.FromBase64String(sKey);
            mCSP.IV = Convert.FromBase64String(sIV);
            mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
            mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
            byt = Encoding.UTF8.GetBytes(str);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Convert.ToBase64String(ms.ToArray());
        }


        //解密
        public string Decrypt3DES(string Value)
        {
            string sKey = "wyw308";
            string sIV = "scf521";
            SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            mCSP.Key = Convert.FromBase64String(sKey);
            mCSP.IV = Convert.FromBase64String(sIV);
            mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
            mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
            byt = Convert.FromBase64String(Value);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Encoding.UTF8.GetString(ms.ToArray());
        }
        /// <summary>
        /// 带指定密钥和矢量的3DES解密
        /// </summary>
        /// <param name="Value"></param>
        /// <param name="sKey"></param>
        /// <param name="sIV"></param>
        /// <returns></returns>
        public string Decrypt3DES(string str, string sKey, string sIV)
        {
            SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            mCSP.Key = Convert.FromBase64String(sKey);
            mCSP.IV = Convert.FromBase64String(sIV);
            mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
            mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
            byt = Convert.FromBase64String(str);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Encoding.UTF8.GetString(ms.ToArray());
        }
        #endregion


        #region 一个简单的加密解密方法,只支持英文
        public static string EnCryptEnStr(string str) //倒序加1加密
        {
            byte[] by = new byte[str.Length];
            for (int i = 0;
             i <= str.Length - 1;
             i++)
            {
                by[i] = (byte)((byte)str[i] + 1);
            }
            str = "";
            for (int i = by.Length - 1;
             i >= 0;
             i--)
            {
                str += ((char)by[i]).ToString();
            }
            return str;
        }
        public static string DeCryptEnStr(string str) //顺序减1解码
        {
            byte[] by = new byte[str.Length];
            for (int i = 0;
             i <= str.Length - 1;
             i++)
            {
                by[i] = (byte)((byte)str[i] - 1);
            }
            str = "";
            for (int i = by.Length - 1;
             i >= 0;
             i--)
            {
                str += ((char)by[i]).ToString();
            }
            return str;
        }
        #endregion


        #region 一个简单的加密解密方法,在上一个的基础上支持中文
        public static string EnCryptCnStr(string str)
        {
            string htext = ""; // blank text


            for (int i = 0; i < str.Length; i++)
            {
                htext = htext + (char)(str[i] + 10 - 1 * 2);
            }
            return htext;
        }


        public static string DeCryptCnStr(string str)
        {
            string dtext = "";


            for (int i = 0; i < str.Length; i++)
            {
                dtext = dtext + (char)(str[i] - 10 + 1 * 2);
            }
            return dtext;
        }
        #endregion


        #region Url地址编码解码


        /// <summary>
        /// 编码Url地址
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string UrlEncode(string url)
        {
            byte[] mByte = null;
            mByte = System.Text.Encoding.GetEncoding("GB2312").GetBytes(url);


            return System.Web.HttpUtility.UrlEncode(mByte);
        }


        /// <summary>
        /// 解码Url地址
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string UrlDecode(string url)
        {
            return HttpUtility.UrlDecode(url, System.Text.Encoding.GetEncoding("GB2312"));
        }
        #endregion
========

.net加密解密技术文章链接

http://www.daxueit.com/article/4733.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值