如何避免加密密钥中的某些字符?

时间:2014-03-23 18:38:40

标签: c# encryption

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

加密方法

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;
    }

解密方法

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#和加密

1 个答案:

答案 0 :(得分:2)

常规base-64在其编码中使用字符/。有些变体对该值使用不同的字符(6位值63),如-+。请改用其中一个。我不知道是否有C#API允许您直接使用变体进行编码,但您可以在编码后用/替换-个字符,然后再切换回来解码。