C#实现3DES加密

来源:互联网 发布:写个代码抢淘宝的月饼 编辑:程序博客网 时间:2024/06/13 01:41

 

 //密钥
        private const string sKey = "abcdefghij!@#$%^&*()1234";
        //矢量,矢量可以为空
        private const string sIV = "qcDY6X+aPLw= ";

///   加密字符串
        ///   输入的字符串
        ///   加密后的字符串
        public static string Encrypt3DES(string a_strString, string a_strKey)
        {
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();

            DES.Key = ASCIIEncoding.UTF8.GetBytes(a_strKey);
            DES.Mode = CipherMode.ECB;

            ICryptoTransform DESEncrypt = DES.CreateEncryptor();

            byte[] Buffer = ASCIIEncoding.UTF8.GetBytes(a_strString);
            return byteToHexStr(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
        }

 /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }

 private void button1_Click(object sender, EventArgs e)
        {

            string ss = Encrypt3DES(textBox1.Text,sKey);
            MessageBox.Show(ss);
                 }