需要加密/解密方法在加密字符串中没有'/'

Cha*_*tur 5 c# asp.net

我需要加密和解密字符串值,例如电子邮件地址和数值,但加密的字符串中不应包含'/',因为我在URL中使用它并使用'/'作为分隔符来获取某些值.

我目前正在使用以下方法:

    string passPhrase = "Pas5pr@se";        // can be any string
    string saltValue = "s@1tValue";        // can be any string
    string hashAlgorithm = "SHA1";             // can be "MD5"
    int passwordIterations = 2;                  // can be any number
    string initVector = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
    int keySize = 256;                // can be 192 or 128

    public string Encrypt(string plainText)
    {            
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);         
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase,saltValueBytes,hashAlgorithm,passwordIterations);
        byte[] keyBytes = password.GetBytes(keySize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();
        symmetricKey.Mode = CipherMode.CBC;            
        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes,initVectorBytes);
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream,encryptor,CryptoStreamMode.Write);           
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);            
        cryptoStream.FlushFinalBlock();
        byte[] cipherTextBytes = memoryStream.ToArray();
        memoryStream.Close();
        cryptoStream.Close();
        string cipherText = Convert.ToBase64String(cipherTextBytes);
        return cipherText;
    }
Run Code Online (Sandbox Code Playgroud)

Osc*_*ros 11

如果您只是为了传递URL,我建议您生成任何加密的字符串(无论是否有/),并执行以下操作:

var sanitized = HttpUtility.UrlEncode(encryptedString);
Run Code Online (Sandbox Code Playgroud)

如你所见,/成为%2f.然后你可以简单地做:

var encryptedString = HttpUtility.UrlDecode(sanitized)
Run Code Online (Sandbox Code Playgroud)

然后你会再次获得相同的字符串.

编辑: HttpUtilitySystem.Web程序集中.