本文介绍了C#中的双转义序列和Rijndael管理的密码学的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将ID传递给网页的QueryString,因为我不想让访问者看到该数字,因此我使用RijndaelManaged算法对其进行了编码,我的问题是,这种加密有时会添加一个字符,例如"+"导致两次转义序列错误.我想知道是否有办法从加密输出中排除一些字符.

I want to pass an id to QueryString of my webpage, as I don't want visitors to see the number, I encode it using RijndaelManaged algorithm, My issue is, this encryption sometimes add a character for example '+' which causes double escape sequence error.I was wondering if there is way to exclude some characters from encryption output.

我的加密代码如下:

  public static  string Encrypt(string plainText)
    {
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
        var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
        var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));

        byte[] cipherTextBytes;

        using (var memoryStream = new MemoryStream())
        {
            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
            {
                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                cryptoStream.FlushFinalBlock();
                cipherTextBytes = memoryStream.ToArray();
                cryptoStream.Close();
            }
            memoryStream.Close();
        }
        return Convert.ToBase64String(cipherTextBytes);
    }

推荐答案

您可以将字节数组转换为十六进制字符串而不是base64字符串.十六进制仅包含[a-f0-9]有关此问题,请参见此问题详细信息.

You could convert your bytearray to a Hex string instead of a base64 string. Hex will only contain [a-f0-9]See this question for details.

但是对于您原来的问题:您应该对查询字符串真正使用URL编码,这将解决+字符的问题.

But as for your original Problem: you should really use URL encoding for your query strings, which will solve the Problem of the + character.

这篇关于C#中的双转义序列和Rijndael管理的密码学的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 12:02