3des 加密解密算

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

 


namespace Common.nx
{
    /// <summary>
    /// tangwf 2011-04-08
    /// 宁夏单点登录加密解密算法
    /// 接口方法为:
    /// http://xxx.xxx.xxx/Logon?SPTokenRequest=SPTokenRequestValue
    /// SPTokenRequestValue的生成算法如下:
    /// Digest = Base64(Hash(ReturnURL + “$”+ TimeStamp))
    /// 其中,Hash算法采用SHA-1。
    /// SPTokenRequestValue = URLEncoding(SPID + “$”+ Base64(Encrypt(ReturnURL + “$”+ TimeStamp + “$”+ Digest)))
    /// 其中,加密算法采用3DES,Key=SPSecret,SPSecret是宁夏WO门户颁发给该SP的密钥。
    /// </summary>
    public class SSOUtil
    {
        /// <summary>
        /// SPSecret是宁夏WO门户颁发给该SP的密钥
        /// </summary>
        //private string nxwoKeyx = "SPSecret";


        /// <summary>
        /// 宁夏3des加密算法
        /// </summary>
        /// <param name="strTobeEnCrypted"></param>
        /// <returns></returns>
        public static string Encrypt(string strTobeEnCrypted)
        {
            string sKey = "D5CDEA8ACEB315089BF7D504D9D0FDE3A77F7526C876526E";
            string sIV = "0102030405060708";

            string str = "";
            if (strTobeEnCrypted == "")
            {
                return "";
            }
            try
            {
                byte[] buffer3;
                byte[] kEY = HexStringToByteArray(sKey);
                byte[] iV = HexStringToByteArray(sIV);
                if (Encrypt(kEY, iV, ConvertStringToByteArray(strTobeEnCrypted), out buffer3))
                {
                    return ToBase64String(buffer3);
                }
                str = "";
            }
            catch
            {
            }
            return str;
        }

        /// <summary>
        /// 带密钥与向量参数的加密方法 输出byte数组形的加密值
        /// </summary>
        /// <param name="KEY"></param>
        /// <param name="IV"></param>
        /// <param name="TobeEncrypted"></param>
        /// <param name="Encrypted"></param>
        /// <returns></returns>
        private static bool Encrypt(byte[] KEY, byte[] IV, byte[] TobeEncrypted, out byte[] Encrypted)
        {
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            Encrypted = null;
            try
            {
                byte[] rgbIV = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };
                for (int i = 0; i < 8; i++)
                {
                    rgbIV[i] = IV[i];
                }
                byte[] rgbKey = new byte[] {
                    0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,
                    0, 1, 2, 3, 4, 5, 6, 7
                 };
                for (int j = 0; j < 0x18; j++)
                {
                    rgbKey[j] = KEY[j];
                }
                Encrypted = des.CreateEncryptor(rgbKey, rgbIV).TransformFinalBlock(TobeEncrypted, 0, TobeEncrypted.Length);
                des.Clear();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }


        /// <summary>
        /// 宁夏解密方法
        /// </summary>
        /// <param name="strTobeDeCrypted"></param>
        /// <returns></returns>
        public static string Decryp(string strTobeDeCrypted)
        {
            string sKey = "D5CDEA8ACEB315089BF7D504D9D0FDE3A77F7526C876526E";
            string sIV = "0102030405060708";
            string str = "";
            if (strTobeDeCrypted == "")
            {
                return "";
            }
            try
            {
                byte[] buffer3;
                byte[] kEY = HexStringToByteArray(sKey);
                byte[] iV = HexStringToByteArray(sIV);
                if (Decrypt(kEY, iV, FromBase64String(strTobeDeCrypted), out buffer3))
                {
                    return ConvertByteArrayToString(buffer3);
                }
                str = "";
            }
            catch
            {
            }
            return str;
        }
        /// <summary>
        /// 带向量与密钥的解密 
        /// </summary>
        /// <param name="KEY"></param>
        /// <param name="IV"></param>
        /// <param name="TobeDecrypted"></param>
        /// <param name="Decrypted"></param>
        /// <returns></returns>
        private static bool Decrypt(byte[] KEY, byte[] IV, byte[] TobeDecrypted, out byte[] Decrypted)
        {
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            Decrypted = null;
            try
            {
                byte[] rgbIV = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };
                for (int i = 0; i < 8; i++)
                {
                    rgbIV[i] = IV[i];
                }
                byte[] rgbKey = new byte[] {
                    0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,
                    0, 1, 2, 3, 4, 5, 6, 7
                 };
                for (int j = 0; j < 0x18; j++)
                {
                    rgbKey[j] = KEY[j];
                }
                Decrypted = des.CreateDecryptor(rgbKey, rgbIV).TransformFinalBlock(TobeDecrypted, 0, TobeDecrypted.Length);
                des.Clear();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }


        /// <summary>
        /// byte数组到字符串
        /// </summary>
        /// <param name="buf"></param>
        /// <returns></returns>
        private static string ConvertByteArrayToString(byte[] buf)
        {
            return Encoding.GetEncoding("utf-8").GetString(buf);
        }

        /// <summary>
        /// 64位字符串到byte数组
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        private static byte[] FromBase64String(string s)
        {
            return Convert.FromBase64String(s);
        }
        /// <summary>
        /// 16进制字符串转byte
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        private static byte[] HexStringToByteArray(string s)
        {
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = (byte)((chr2hex(s.Substring(i * 2, 1)) * 0x10) + chr2hex(s.Substring((i * 2) + 1, 1)));
            }
            return buffer;
        }

        /// <summary>
        /// 16进制到byte转换
        /// </summary>
        /// <param name="chr"></param>
        /// <returns></returns>
        private static byte chr2hex(string chr)
        {
            switch (chr)
            {
                case "0":
                    return 0;

                case "1":
                    return 1;

                case "2":
                    return 2;

                case "3":
                    return 3;

                case "4":
                    return 4;

                case "5":
                    return 5;

                case "6":
                    return 6;

                case "7":
                    return 7;

                case "8":
                    return 8;

                case "9":
                    return 9;

                case "A":
                    return 10;

                case "B":
                    return 11;

                case "C":
                    return 12;

                case "D":
                    return 13;

                case "E":
                    return 14;

                case "F":
                    return 15;
            }
            return 0;
        }
       
        /// <summary>
        /// 字符串到byte数组
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        private static byte[] ConvertStringToByteArray(string s)
        {
            return Encoding.GetEncoding("utf-8").GetBytes(s);
        }
        /// <summary>
        /// byte数组到base64字符串
        /// </summary>
        /// <param name="buf"></param>
        /// <returns></returns>
        private static string ToBase64String(byte[] buf)
        {
            return Convert.ToBase64String(buf);
        }


        /// <summary>
        /// 32位加密 
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string EncryptDes(string source)
        {
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            string str = null;

            SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
            string sKey = "qJzGEh6hESZDVJeCnFPGuxzaiB7NLQM3";
            string sIV = "qcDY6X+aPLw=";
            //string sIV = Base64StringToString("0102030405060708");
            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(source);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            str = Convert.ToBase64String(ms.ToArray());

            return str;

        }


        public static string DecryptDes(string source)
        {
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            string str = null;

            SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
            int i = mCSP.BlockSize;
            int blocksize = i;
            string sKey = "qJzGEh6hESZDVJeCnFPGuxzaiB7NLQM3";
            string sIV = "qcDY6X+aPLw="; //IV的字节数必须等于SymmetricAlgorithm.BlockSize/8
            //string sIV = Base64StringToString("0102030405060708");

            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(source);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            str = Encoding.UTF8.GetString(ms.ToArray());
            return str;

        }


        /// <summary>
        /// tangwf 2011-04-11 des3加密算法
        /// </summary>
        /// <param name="desText">加密串</param>
        /// <param name="desKey">key</param>
        /// <returns></returns>
        public static string DES3Encrypt(string desText, string desKey)
        {
            string strRtnValue = "";
            try
            {
                TripleDES threedes = new TripleDESCryptoServiceProvider();

                //默认的TripleDESCryptoServiceProvider的key为24字节,IV为8字节,加密数据块为8字节
                threedes.Key = StringToByte(desKey, 24); // convert to 24 characters - 192 bits
                //threedes.Key = StringToByteForHex(desKey);
                //threedes.Key = StringToByte(desKey, 48);
                //初始向量
                threedes.IV = StringToByte("12345678");
                //threedes.IV = StringToByteForHex("0102030405060708");
                //threedes.IV = StringToByte("0102030405060708");
                byte[] key = threedes.Key;
                byte[] IV = threedes.IV;

                ICryptoTransform encryptor = threedes.CreateEncryptor(key, IV);

                MemoryStream msEncrypt = new MemoryStream();
                CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

                // Write all data to the crypto stream and flush it.
                csEncrypt.Write(StringToByte(desText), 0, StringToByte(desText).Length);
                csEncrypt.FlushFinalBlock();

                // Get the encrypted array of bytes.
                byte[] encrypted = msEncrypt.ToArray();
               
                //加密后的字符串
                strRtnValue = ByteToString(encrypted);

               
            }
            catch (Exception ex)
            {
                ex.ToString();
                strRtnValue =  "";
            }
            return strRtnValue;
        }


        /// <summary>
        /// tangwf 2011-04-11 des3解密算法
        /// </summary>
        /// <param name="desText">加密串</param>
        /// <param name="desKey">key</param>
        /// <returns></returns>
        public static string DES3Decrypt(string DecText, string DecKey)
        {
            string strRtnValue = "";
            try
            {
                TripleDESCryptoServiceProvider threedes = new TripleDESCryptoServiceProvider();

                //默认的TripleDESCryptoServiceProvider的key为24字节,IV为8字节,加密数据块为8字节
                threedes.Key = StringToByte(DecKey, 24);
                //threedes.Key = StringToByteForHex(DecKey);
                //threedes.Key = StringToByte(DecKey, 48);
                //初始向量
                threedes.IV = StringToByte("12345678");
                //threedes.IV = StringToByteForHex("0102030405060708");
                //threedes.IV = StringToByte("0102030405060708");

                byte[] key = threedes.Key;
                byte[] IV = threedes.IV;
                //threedes.Mode = CipherMode.ECB;
                //threedes.Padding = PaddingMode.PKCS7;

                byte[] decryptarry = StringToByteForHex(DecText);

                ICryptoTransform decryptor = threedes.CreateDecryptor(key, IV);


                MemoryStream msDecrypt = new MemoryStream(decryptarry);

                //CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

                CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

                //StreamReader reader = new StreamReader(csDecrypt, System.Text.Encoding.Unicode);
                ///return reader.ReadToEnd();
                //解 密字符串s =  ByteToString(csDecrypt);
                //strRtnValue = ByteToString(csDecrypt);
                strRtnValue = ByteToString(csDecrypt);
                //byte[] DecryptDataArray = new byte[DecText.Length];

                //csDecrypt.Read(DecryptDataArray, 0, DecryptDataArray.Length);

                msDecrypt.Close();

                csDecrypt.Close();

 

            }
            catch (Exception ex)
            {
                ex.ToString();
                strRtnValue = "";
            }
            return strRtnValue;
        }


        #region 字符串与byte互相转换
        /*------------------------------------------------------------------------------------------------------------------------------------------*/
        /// <summary>
        /// 将普通文本转换成Base64编码的文本
        /// </summary>
        /// <param name="value">普通文本</param>
        /// <returns></returns>
        public static string StringToBase64String(String value)
        {
            byte[] binBuffer = (new UnicodeEncoding()).GetBytes(value);
            int base64ArraySize = (int)Math.Ceiling(binBuffer.Length / 3d) * 4;
            char[] charBuffer = new char[base64ArraySize];
            Convert.ToBase64CharArray(binBuffer, 0, binBuffer.Length, charBuffer, 0);
            string s = new string(charBuffer);
            return s;
        }

        /// <summary>
        /// 将Base64编码的文本转换成普通文本
        /// </summary>
        /// <param name="base64">Base64编码的文本</param>
        /// <returns></returns>
        public static string Base64StringToString(string base64)
        {
            char[] charBuffer = base64.ToCharArray();
            byte[] bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length);
            return (new UnicodeEncoding()).GetString(bytes);
        }

        /// <summary>
        /// 将Byte[]转换成Base64编码文本
        /// </summary>
        /// <param name="binBuffer">Byte[]</param>
        /// <returns></returns>
        public string toBase64(byte[] binBuffer)
        {
            int base64ArraySize = (int)Math.Ceiling(binBuffer.Length / 3d) * 4;
            char[] charBuffer = new char[base64ArraySize];
            Convert.ToBase64CharArray(binBuffer, 0, binBuffer.Length, charBuffer, 0);
            string s = new string(charBuffer);
            return s;
        }

        /// <summary>
        /// 将Base64编码文本转换成Byte[]
        /// </summary>
        /// <param name="base64">Base64编码文本</param>
        /// <returns></returns>
        public Byte[] Base64ToBytes(string base64)
        {
            char[] charBuffer = base64.ToCharArray();
            byte[] bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length);
            return bytes;
        }


        /// <summary>
        /// 十六进制内容转换为byte数组
        /// </summary>
        /// <param name="StringToConvert"></param>
        /// <returns></returns>
        public static byte[] StringToByteForHex(string StringToConvert)
        {
           
            char[] CharArray = StringToConvert.ToCharArray();
            byte[] ByteArray = new byte[CharArray.Length/2];
            int j = 0;
            for (int i = 0; i < CharArray.Length; i=i+2)
            {
                int intValue = Convert.ToInt32(CharArray[i].ToString() + CharArray[i + 1].ToString(), 16);
                byte b = Convert.ToByte(intValue);
                ByteArray[j] = b;
                j++;
            }
            return ByteArray;
        }
        public static byte[] StringToByte(string StringToConvert)
        {

            char[] CharArray = StringToConvert.ToCharArray();
            byte[] ByteArray = new byte[CharArray.Length];
            for (int i = 0; i < CharArray.Length; i++)
            {
                ByteArray[i] = Convert.ToByte(CharArray[i]);
            }
            return ByteArray;
        }
        public static byte[] StringToByte(string StringToConvert, int length)
        {

            char[] CharArray = StringToConvert.ToCharArray();
            byte[] ByteArray = new byte[length];
            for (int i = 0; i < CharArray.Length; i++)
            {
                ByteArray[i] = Convert.ToByte(CharArray[i]);
            }
            return ByteArray;
        }
        public static string ByteToString(CryptoStream buff)
        {
            string sbinary = "";
            int b = 0;
            do
            {
                b = buff.ReadByte();
                if (b != -1) sbinary += ((char)b);

            } while (b != -1);
            return (sbinary);
        }
        public static string ByteToString(byte[] buff)
        {
            string sbinary = "";
            for (int i = 0; i < buff.Length; i++)
            {
                sbinary += buff[i].ToString("X2"); // hex format
            }
            return (sbinary);
        }


        #endregion 字符串与byte互相转换
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值