• C# DES算法加密解密


           private void DES()
            {
                string myKey = GenerateKey();
                string a = DESEncrypt(textBox1.Text, myKey);
                string b = DESDecrypt(a, myKey);
                MessageBoxEx.Show(myKey + Environment.NewLine + a + Environment.NewLine + b);
            }
            //创建密钥
            public static string GenerateKey()
            {
                DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
                return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
            }

            ///DES加密
            public static string DESEncrypt(string pToEncrypt, string sKey)
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }
                ret.ToString();
                return ret.ToString();
            }

            ///DES解密
            public static string DESDecrypt(string pToDecrypt, string sKey)
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
                for (int x = 0; x < pToDecrypt.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }

                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                return System.Text.Encoding.Default.GetString(ms.ToArray());
            }

    作者:chhuic

    出处:http://chhuic.cnblogs.com
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    为了我们自己的利益,请不要去支持番茄花园。
    游戏版本比较的算法[ZZ]
    DXUT框架剖析(9)
    强制删除任意文件以及文件夹
    安全幻想曲2008
    DXUT框架剖析(12)
    DXUT框架剖析(6)
    [Ph4nt0m] [zz]The Emergence Of A Theme
    俄国农民乘法
    写在msn签名上的I'M 计划
  • 原文地址:https://www.cnblogs.com/chhuic/p/1607985.html
Copyright © 2020-2023  润新知