C# DES加解密

    public static string EncodeDES(string text, string Key)
        {
            byte[] keyBytes = Encoding.ASCII.GetBytes(Key.Substring(0, 8));
            byte[] keyIV = keyBytes;
            byte[] inputByteArray = Encoding.UTF8.GetBytes(text);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

            provider.Mode = CipherMode.ECB;//兼容其他语言的Des加密算法  
            provider.Padding = PaddingMode.PKCS7;//自动补0

            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();

            return Convert.ToBase64String(mStream.ToArray());
         
        }


        public static string DecodeDES(string text, string key)
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
            byte[] keyIV = keyBytes;
            byte[] inputByteArray = Convert.FromBase64String(text);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            provider.Padding = PaddingMode.PKCS7;
            provider.Mode = CipherMode.ECB;//兼容其他语言的Des加密算法  
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Encoding.UTF8.GetString(mStream.ToArray());
        }
View Code

 

posted @ 2021-02-23 14:16  隨興∥隨心  阅读(25)  评论(0编辑  收藏  举报