UrlEncoding Plus(+) in URL in ASP.Net

2019-07-06 01:55发布

I'm encrypting and Base64 a string. Everything works great, until I retrieve the encrypted string from the QueryString collection. The Encrypted text contains a plus symbol. When I retrieve the encrypted string, where a plus once was there is now a space. As you can imagine this doesn't decrypt.

I have tried both Server.HtmlEncode/HtmlDecode and Server.UrlEncode/Server.UrlDecode with no avail. Both methods confuse the plus symbol with the space.

Any idea's?

Here is a similar post: QueryString Malformed

Edit: I found the solution: Server.UrlEncode does work, I was applying Server.UrlDecode and didn't need too.

标签: asp.net url
2条回答
我想做一个坏孩纸
2楼-- · 2019-07-06 02:18

I had problems like you few years ago. Here's my code to decode base64 query string to string and vise versa

    public static String DoDecryption(String Value)
    {
        Decryptor dec = new Decryptor(EncryptionAlgorithm.TripleDes );
        dec.IV = Encoding.ASCII.GetBytes("funky");
        byte [] DecValue =  Convert.FromBase64String(Value.Replace("+++","=="));
        byte [] DecKey   = Encoding.ASCII.GetBytes("0123456789012345");
        byte [] DecipherValue = dec.Decrypt(DecValue,DecKey);
        return Encoding.ASCII.GetString(DecipherValue);
    }

and here is the encryption part

    public static String DoEncryption(String Value)
    {
        Encryptor enc = new Encryptor(EncryptionAlgorithm.TripleDes);
        byte [] EncValue =  Encoding.ASCII.GetBytes(Value);
        byte [] EncKey   = Encoding.ASCII.GetBytes("0123456789012345");
        enc.IV = Encoding.ASCII.GetBytes("funky");
        byte [] CipherValue = enc.Encrypt(EncValue,EncKey);
        //InitVector = Encoding.ASCII.GetString(enc.IV);
        return Convert.ToBase64String(CipherValue).Replace("==","+++");
    }

Note that Value parameter in DoEncryption is the string you want to encrypt into querystring and value parameter in DoDecryption is query string that already convert into base64 string.

Hope thats help

查看更多
▲ chillily
3楼-- · 2019-07-06 02:39

Be careful, the method of substituting "+++" for "==" is dangerous because in rare situations, it is possible for an encrypted query string to validly contain "+++". In this case, the decryption fails. For a better solution to the problem, look at using the "modified base64 for url". It involves switching out "-" for "+" and "_" for "/" and has no "==" padding. It seems to be working for us, even in situations where the other failed. Here is the link I used for reference that is working for us.

Code for decoding/encoding a modified base64 URL

查看更多
登录 后发表回答