ASP.NET : Hide Querystring in URL

前端 未结 5 702
夕颜
夕颜 2020-12-20 00:16

I don\'t know if I\'m just being overly hopeful, but is there a way to hide the query string returned in the URL?

The scenario I am in is where I have page1.aspx red

5条回答
  •  眼角桃花
    2020-12-20 01:08

    Awhile back I made some http encoding encrypt/decrypt methods for this purpose. Sometimes in asp.net you need to use the query string, but you also need the end user to not know the value. What I do is base 64 encode, encrypt the value, hash the value based on my private key, and stick them together with a -. On the other side I check the left side hash to verify authenticity, and decrypt the right side. One really nice gotcha is that + (which is a valid base64 string value) is equal to space in html encoding, so I take that into account in the decrypt.

    The way I use this is add the encrypted value to the query string, and then decrypt it on the other side

        private const string KEY = "";
    
        public static string EncryptAndHash(this string value)
        {
            MACTripleDES des = new MACTripleDES();
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            des.Key = md5.ComputeHash(Encoding.UTF8.GetBytes(KEY));
            string encrypted = Convert.ToBase64String(des.ComputeHash(Encoding.UTF8.GetBytes(value))) + '-' + Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
    
            return HttpUtility.UrlEncode(encrypted);
        }
    
        /// 
        /// Returns null if string has been modified since encryption
        /// 
        /// 
        /// 
        public static string DecryptWithHash(this string encoded)
        {
            MACTripleDES des = new MACTripleDES();
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            des.Key = md5.ComputeHash(Encoding.UTF8.GetBytes(KEY));
    
            string decoded = HttpUtility.UrlDecode(encoded);
            // in the act of url encoding and decoding, plus (valid base64 value) gets replaced with space (invalid base64 value). this reverses that.
            decoded = decoded.Replace(" ", "+");
            string value = Encoding.UTF8.GetString(Convert.FromBase64String(decoded.Split('-')[1]));
            string savedHash = Encoding.UTF8.GetString(Convert.FromBase64String(decoded.Split('-')[0]));
            string calculatedHash = Encoding.UTF8.GetString(des.ComputeHash(Encoding.UTF8.GetBytes(value)));
    
            if (savedHash != calculatedHash) return null;
    
            return value;
        }
    

提交回复
热议问题