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

 namespace Common
namespace Common


 {
{

 /**//**/
    /**//**/

 /**//// <summary>
    /**//// <summary>
 /// 加密,解密功能函数
    /// 加密,解密功能函数
 /// </summary>
    /// </summary> 
 public class EncryptionUtil
    public class EncryptionUtil

 
     {
{
 public EncryptionUtil()
        public EncryptionUtil()

 
         {
{
 //
            //
 // TODO: Add constructor logic here
            // TODO: Add constructor logic here
 //
            // 

 }
        }

 static private Byte[] m_Key = new Byte[8];
        static private Byte[] m_Key = new Byte[8];
 static private Byte[] m_IV = new Byte[8];
        static private Byte[] m_IV = new Byte[8];

 //为了安全,直接将key写死在文件中,你也可以用一个属性来实现
        //为了安全,直接将key写死在文件中,你也可以用一个属性来实现 
 public string key = "(@jhtchina@)";
        public string key = "(@jhtchina@)";


 /**//**/
        /**//**/

 /**///////////////////////////
        /**/////////////////////////// 
 //加密函数
        //加密函数 
 public string EncryptData(String strKey, String strData)
        public string EncryptData(String strKey, String strData)

 
         {
{
 string strResult; //Return Result
            string strResult; //Return Result

 //1. 字符大小不能超过 90Kb. 否则, 缓存容易溢出(看第3点)
            //1. 字符大小不能超过 90Kb. 否则, 缓存容易溢出(看第3点) 
 if (strData.Length > 92160)
            if (strData.Length > 92160)

 
             {
{
 strResult = "Error. Data String too large. Keep within 90Kb.";
                strResult = "Error. Data String too large. Keep within 90Kb.";
 return strResult;
                return strResult;
 }
            }

 //2. 生成key
            //2. 生成key 
 if (!InitKey(strKey))
            if (!InitKey(strKey))

 
             {
{
 strResult = "Error. Fail to generate key for encryption";
                strResult = "Error. Fail to generate key for encryption";
 return strResult;
                return strResult;
 }
            }

 //3. 准备处理的字符串
            //3. 准备处理的字符串
 //字符串的前5个字节用来存储数据的长度
            //字符串的前5个字节用来存储数据的长度
 //用这个简单的方法来记住数据的初始大小,没有用太复杂的方法
            //用这个简单的方法来记住数据的初始大小,没有用太复杂的方法 
 strData = String.Format("{0,5:00000}" + strData, strData.Length);
            strData = String.Format("{0,5:00000}" + strData, strData.Length);


 //4. 加密数据
            //4. 加密数据 
 byte[] rbData = new byte[strData.Length];
            byte[] rbData = new byte[strData.Length];
 ASCIIEncoding aEnc = new ASCIIEncoding();
            ASCIIEncoding aEnc = new ASCIIEncoding();
 aEnc.GetBytes(strData, 0, strData.Length, rbData, 0);
            aEnc.GetBytes(strData, 0, strData.Length, rbData, 0);
 //加密功能实现的主要类
            //加密功能实现的主要类 
 DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
            DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();

 ICryptoTransform desEncrypt = descsp.CreateEncryptor(m_Key, m_IV);
            ICryptoTransform desEncrypt = descsp.CreateEncryptor(m_Key, m_IV);


 //5. 准备stream
            //5. 准备stream
 // mOut是输出流.
            // mOut是输出流.
 // mStream是输入流
            // mStream是输入流
 // cs为转换流
            // cs为转换流 
 MemoryStream mStream = new MemoryStream(rbData);
            MemoryStream mStream = new MemoryStream(rbData);
 CryptoStream cs = new CryptoStream(mStream, desEncrypt, CryptoStreamMode.Read);
            CryptoStream cs = new CryptoStream(mStream, desEncrypt, CryptoStreamMode.Read);
 MemoryStream mOut = new MemoryStream();
            MemoryStream mOut = new MemoryStream();

 //6. 开始加密
            //6. 开始加密 
 int bytesRead;
            int bytesRead;
 byte[] output = new byte[1024];
            byte[] output = new byte[1024];
 do
            do

 
             {
{
 bytesRead = cs.Read(output, 0, 1024);
                bytesRead = cs.Read(output, 0, 1024);
 if (bytesRead != 0)
                if (bytesRead != 0)
 mOut.Write(output, 0, bytesRead);
                    mOut.Write(output, 0, bytesRead);
 } while (bytesRead > 0);
            } while (bytesRead > 0);

 //7. 返回加密结果
            //7. 返回加密结果
 //因为是一个web项目,在这里转换为base64,因此在http上是不会出错的
            //因为是一个web项目,在这里转换为base64,因此在http上是不会出错的 
 if (mOut.Length == 0)
            if (mOut.Length == 0)
 strResult = "";
                strResult = "";
 else
            else
 strResult = Convert.ToBase64String(mOut.GetBuffer(), 0, (int)mOut.Length);
                strResult = Convert.ToBase64String(mOut.GetBuffer(), 0, (int)mOut.Length);

 return strResult;
            return strResult;
 }
        }


 /**//**/
        /**//**/

 /**///////////////////////////
        /**/////////////////////////// 
 //解密函数
        //解密函数 
 public string DecryptData(String strKey, String strData)
        public string DecryptData(String strKey, String strData)

 
         {
{
 string strResult;
            string strResult;

 //1. 生成解密key
            //1. 生成解密key 
 if (!InitKey(strKey))
            if (!InitKey(strKey))

 
             {
{
 strResult = "Error. Fail to generate key for decryption";
                strResult = "Error. Fail to generate key for decryption";
 return strResult;
                return strResult;
 }
            }

 //2. 初始化解密的主要类
            //2. 初始化解密的主要类 
 int nReturn = 0;
            int nReturn = 0;
 DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
            DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
 ICryptoTransform desDecrypt = descsp.CreateDecryptor(m_Key, m_IV);
            ICryptoTransform desDecrypt = descsp.CreateDecryptor(m_Key, m_IV);

 //3. 准备stream
            //3. 准备stream
 // mOut为输出流
            // mOut为输出流
 // cs为转换流
            // cs为转换流 
 MemoryStream mOut = new MemoryStream();
            MemoryStream mOut = new MemoryStream();
 CryptoStream cs = new CryptoStream(mOut, desDecrypt, CryptoStreamMode.Write);
            CryptoStream cs = new CryptoStream(mOut, desDecrypt, CryptoStreamMode.Write);

 byte[] bPlain = new byte[strData.Length];
            byte[] bPlain = new byte[strData.Length];
 try
            try

 
             {
{
 bPlain = Convert.FromBase64CharArray(strData.ToCharArray(), 0, strData.Length);
                bPlain = Convert.FromBase64CharArray(strData.ToCharArray(), 0, strData.Length);
 }
            }
 catch (Exception)
            catch (Exception)

 
             {
{
 strResult = "Error. Input Data is not base64 encoded.";
                strResult = "Error. Input Data is not base64 encoded.";
 return strResult;
                return strResult;
 }
            }

 long lRead = 0;
            long lRead = 0;
 long lTotal = strData.Length;
            long lTotal = strData.Length;

 try
            try

 
             {
{
 //5. 完成解密
                //5. 完成解密 
 while (lTotal >= lRead)
                while (lTotal >= lRead)

 
                 {
{
 cs.Write(bPlain, 0, (int)bPlain.Length);
                    cs.Write(bPlain, 0, (int)bPlain.Length);
 lRead = mOut.Length + Convert.ToUInt32(((bPlain.Length / descsp.BlockSize) * descsp.BlockSize));
                    lRead = mOut.Length + Convert.ToUInt32(((bPlain.Length / descsp.BlockSize) * descsp.BlockSize));
 };
                };

 ASCIIEncoding aEnc = new ASCIIEncoding();
                ASCIIEncoding aEnc = new ASCIIEncoding();
 strResult = aEnc.GetString(mOut.GetBuffer(), 0, (int)mOut.Length);
                strResult = aEnc.GetString(mOut.GetBuffer(), 0, (int)mOut.Length);

 //6.去处存储长度的前5个字节的数据
                //6.去处存储长度的前5个字节的数据 
 String strLen = strResult.Substring(0, 5);
                String strLen = strResult.Substring(0, 5);
 int nLen = Convert.ToInt32(strLen);
                int nLen = Convert.ToInt32(strLen);
 strResult = strResult.Substring(5, nLen);
                strResult = strResult.Substring(5, nLen);
 nReturn = (int)mOut.Length;
                nReturn = (int)mOut.Length;

 return strResult;
                return strResult;
 }
            }
 catch (Exception)
            catch (Exception)

 
             {
{
 strResult = "Error. Decryption Failed. Possibly due to incorrect Key or corrputed data";
                strResult = "Error. Decryption Failed. Possibly due to incorrect Key or corrputed data";
 return strResult;
                return strResult;
 }
            }
 }
        }


 /**//**/
        /**//**/

 /**//////////////////////////////////////////////////////////////
        /**////////////////////////////////////////////////////////////// 
 //生成key的函数
        //生成key的函数 
 static private bool InitKey(String strKey)
        static private bool InitKey(String strKey)

 
         {
{
 try
            try

 
             {
{
 // 转换key为字节流
                // 转换key为字节流 
 byte[] bp = new byte[strKey.Length];
                byte[] bp = new byte[strKey.Length];
 ASCIIEncoding aEnc = new ASCIIEncoding();
                ASCIIEncoding aEnc = new ASCIIEncoding();
 aEnc.GetBytes(strKey, 0, strKey.Length, bp, 0);
                aEnc.GetBytes(strKey, 0, strKey.Length, bp, 0);

 SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
                SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
 byte[] bpHash = sha.ComputeHash(bp);
                byte[] bpHash = sha.ComputeHash(bp);

 int i;
                int i;
 // 生成初始化DESCryptoServiceProvider的参数
                // 生成初始化DESCryptoServiceProvider的参数 
 for (i = 0; i < 8; i++)
                for (i = 0; i < 8; i++)
 m_Key[i] = bpHash[i];
                    m_Key[i] = bpHash[i];

 for (i = 8; i < 16; i++)
                for (i = 8; i < 16; i++)
 m_IV[i - 8] = bpHash[i];
                    m_IV[i - 8] = bpHash[i];

 return true;
                return true;
 }
            }
 catch (Exception)
            catch (Exception)

 
             {
{
 //错误处理
                //错误处理 
 return false;
                return false;
 }
            }
 }
        }
 }
    }
 }
}




 /**//*
/**//*
 using System;
      using System;
 using System.Collections.Generic;
using System.Collections.Generic;
 using System.Text;
using System.Text;

 using NUnit.Framework;
using NUnit.Framework;

 namespace test11
namespace test11
 {
{
 [TestFixture]
    [TestFixture]
 public class Class1
    public class Class1
 {
    {
 
        
 public string test111(string currentValue)
        public string test111(string currentValue)
 {
        {
 //Console.Out.Write("11");
            //Console.Out.Write("11");
 EncryptionUtil EU = new EncryptionUtil();
            EncryptionUtil EU = new EncryptionUtil();
 //int count = Convert.ToInt32(EU.DecryptData(EU.key, currentValue));
            //int count = Convert.ToInt32(EU.DecryptData(EU.key, currentValue));
 return EU.DecryptData(EU.key, EU.DecryptData(EU.key, currentValue));
            return EU.DecryptData(EU.key, EU.DecryptData(EU.key, currentValue));
 }
        }

 public string test222(string currentValue)
        public string test222(string currentValue)
 {
        {
 
           
 EncryptionUtil EU = new EncryptionUtil();
            EncryptionUtil EU = new EncryptionUtil();
 return EU.EncryptData(EU.key, EU.EncryptData(EU.key, currentValue));
            return EU.EncryptData(EU.key, EU.EncryptData(EU.key, currentValue));
 }
        }

 [Test]
        [Test]
 public void test_Main()
        public void test_Main()
 {
        {
 string str_Pass = test222("0123456789");
            string str_Pass = test222("0123456789");
 Console.Out.WriteLine(str_Pass);
            Console.Out.WriteLine(str_Pass);
 string str_Number = test111(str_Pass);
            string str_Number = test111(str_Pass);
 Console.Out.WriteLine(str_Number);
            Console.Out.WriteLine(str_Number);
 }
        }
 }
    }
 }
}

 */
*/
 //
//
 //
// 
		 
		posted @ 
2007-08-23 18:02 
jhtchina 
阅读(
505) 
评论() 
 
收藏 
举报