如何避免加密密钥中出现某些字符

本文关键字:字符 何避免 加密 密钥 | 更新日期: 2023-09-27 17:52:37

我有两个方法,一个加密,另一个解密:

<<p> 加密方法/strong>
public static string Encrypt(string EncryptionMessage)
    {
        string Encrypted = string.Empty;
        string EncryptionKey = "0123456789";
        byte[] clearBytes = Encoding.Unicode.GetBytes(EncryptionMessage);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms,   encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                Encrypted = Convert.ToBase64String(ms.ToArray());
            }
        }
        return Encrypted;
    }
<<p> 解密方法/strong>
public static string Decrypt(string cipherText)
    {
        string Decrypted = string.Empty;
        string EncryptionKey = "0123456789";
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                Decrypted = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return Decrypted;
    }

加密后的密钥总是返回以下字符:'/。我想避免加密密钥返回字符'/

帮忙吗?

PS:语言是c#,我已经标记了它,我看到的是c#,但其他人看到的是另一种语言。我标记了c#和加密

如何避免加密密钥中出现某些字符

传统的base-64在编码中使用字符/。还有一些变体使用不同的字符表示该值(6位值63),如-+。用其中一种吧。我不知道是否有c# API允许您直接使用变体进行编码,但您可以在编码后将/字符替换为-,然后在解码之前将它们切换回来。