C# DES加解密ECB模式

    static void Main(string[] args)
        {
            System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
            //加密字符串   秘钥 IV
            var str = DESEncrypt("cs-123-1594971950656", "553036673260679053754558", "12345678");
            var result = DESDecrypst(str, "553036673260679053754558", "12345678");


            Console.ReadKey();
        }
        /// <summary>
        /// ECB加密
        /// </summary>
        /// <param name="paymentCode">加密字符串</param>
        /// <param name="key">秘钥</param>
        /// <param name="iv">ECB模式不需要IV</param>
        /// <returns></returns>
        public static string DESEncrypt(string paymentCode, string key, string iv)
        {
            SymmetricAlgorithm symmetric;
            ICryptoTransform iCrypto;
            MemoryStream memory;
            CryptoStream crypto;
            byte[] byt;
            symmetric = new TripleDESCryptoServiceProvider();
            symmetric.Key = Encoding.UTF8.GetBytes(key);
            symmetric.IV = Encoding.UTF8.GetBytes(iv);
            symmetric.Mode = CipherMode.ECB;
            symmetric.Padding = PaddingMode.PKCS7;


            iCrypto = symmetric.CreateEncryptor();
            byt = Encoding.UTF8.GetBytes(paymentCode);
            memory = new MemoryStream();
            crypto = new CryptoStream(memory, iCrypto, CryptoStreamMode.Write);
            crypto.Write(byt, 0, byt.Length);
            crypto.FlushFinalBlock();
            crypto.Close();
            return Convert.ToBase64String(memory.ToArray());
        }

        /// <summary>
        /// ECB解密
        /// </summary>
        /// <param name="data">解密字符串</param>
        /// <param name="key">秘钥</param>
        /// <param name="iv">ECB模式不需要IV</param>
        /// <returns></returns>
        public static string DESDecrypst(string data, string key, string iv)
        {
            SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();

            mCSP.Key = Encoding.UTF8.GetBytes(key);
            mCSP.IV = Encoding.UTF8.GetBytes(iv);
            mCSP.Mode = CipherMode.ECB;
            mCSP.Padding = PaddingMode.PKCS7;

            ICryptoTransform iCrypto;
            MemoryStream memory;
            CryptoStream crypto;
            byte[] byt;
            iCrypto = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);

            byt = Convert.FromBase64String(data);
            memory = new MemoryStream();
            crypto = new CryptoStream(memory, iCrypto, CryptoStreamMode.Write);
            crypto.Write(byt, 0, byt.Length);
            crypto.FlushFinalBlock();
            crypto.Close();
            return Encoding.UTF8.GetString(memory.ToArray());
        }

 

posted @ 2020-07-17 17:16  渴死的鱼丶  阅读(2489)  评论(0编辑  收藏  举报