分享

asp.net URL参数加密解密的问题

 mybook564 2014-09-15


  最近我遇到一个关于asp.net
URL参数加密解密的问题,在加密时没问题,可是解密就有问题了,有些参数解密出来是空(并不是原来的数据)。下面是一个需要加密URL参数的地
址:http://www.px?username=marry&password=marry

  在index.aspx页添加的代码:

        private static byte[] key = { };

        private static byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

        private static string EncryptionKey = "!5623a#de"; 

        public static string Encrypt(string Input)

        {

            try

            {

                key = System.Text.Encoding.UTF8.GetBytes(EncryptionKey.Substring(0, 8));

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                Byte[] inputByteArray = Encoding.UTF8.GetBytes(Input);

                MemoryStream ms = new MemoryStream();

                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);

                cs.Write(inputByteArray, 0, inputByteArray.Length);

                cs.FlushFinalBlock();

                return Convert.ToBase64String(ms.ToArray());

            }

            catch (Exception ex)

            {

                return "";

            }

        }

        Response.Redirect(“http://www.px?username=” + Encrypt(marry) + "&password=" Encrypt(marry

));



  在px网页需要的代码:

        private static byte[] key = { };

        private static byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

        private static string EncryptionKey = "!5623a#de";


       public static string Decrypt(string Input)

        {

            if (!string.IsNullOrEmpty(Input))

            {

                Input = Input.Replace(" ", "+");


                Byte[] inputByteArray = new Byte[Input.Length];

                try

                {

                    key = System.Text.Encoding.UTF8.GetBytes(EncryptionKey.Substring(0, 8));

                    DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                    inputByteArray = Convert.FromBase64String(Input);

                    MemoryStream ms = new MemoryStream();

                    CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);

                    cs.Write(inputByteArray, 0, inputByteArray.Length);

                    cs.FlushFinalBlock();


                    Encoding encoding = Encoding.UTF8;

                    return encoding.GetString(ms.ToArray());


                }

                catch (Exception ex)

                {

                    return "";

                }

            }

            else

            {

                return "";

            }

        }

在Page_Load事件中要添加的代码:

            Decrypt(Request.QueryString["username"]);

            Decrypt(Request.QueryString["password"]);



总结:如果去除红色部分的代码就会出现上面出现所说的情况,出错或者解密出来的数据变成空值。


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约