如何加密可能包含非基本64个字符的字符串

时间:2016-11-03 16:25:21

标签: c# .net winforms encryption base64

更新:问题是!我犯了一个错误,否则两个Cods(下面和 PS 的那个都是正确的)但是仍然感谢来自@Luke Park的很好的回答,我学到了一些新东西。

我不熟悉加密/解密算法,因此我在网上搜索并找到了这个类:

Encrypting & Decrypting a String in C#

代码是: (我在Decrypt方法中添加了一个Try / Catch,以防密码错误return "";

using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Linq;

namespace EncryptStringSample
{
    public static class StringCipher
    {
        // This constant is used to determine the keysize of the encryption algorithm in bits.
        // We divide this by 8 within the code below to get the equivalent number of bytes.
        private const int Keysize = 256;

        // This constant determines the number of iterations for the password bytes generation function.
        private const int DerivationIterations = 1000;

        public static string Encrypt(string plainText, string passPhrase)
        {
            // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
            // so that the same Salt and IV values can be used when decrypting.  
            var saltStringBytes = Generate256BitsOfRandomEntropy();
            var ivStringBytes = Generate256BitsOfRandomEntropy();
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                                var cipherTextBytes = saltStringBytes;
                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                                memoryStream.Close();
                                cryptoStream.Close();
                                return Convert.ToBase64String(cipherTextBytes);
                            }
                        }
                    }
                }
            }
        }

    public static string Decrypt(string cipherText, string passPhrase)
    {
        // Get the complete stream of bytes that represent:
        // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
        var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
        // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
        var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
        // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
        var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
        // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
        var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();
        try
        {
            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream(cipherTextBytes))
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                            {
                                var plainTextBytes = new byte[cipherTextBytes.Length];
                                var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                memoryStream.Close();
                                cryptoStream.Close();
                                return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                            }
                        }
                    }
                }
            }
        }
        catch (Exception)
        {
            return "";
        }
    }

        private static byte[] Generate256BitsOfRandomEntropy()
        {
            var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits.
            using (var rngCsp = new RNGCryptoServiceProvider())
            {
                // Fill the array with cryptographically secure random bytes.
                rngCsp.GetBytes(randomBytes);
            }
            return randomBytes;
        }
    }
}

我在我的应用程序中使用了这个类:

string plaintext = "InsertedPasswordByUserToEncrypt";
string password = plaintext; // use its own password as encryption key
string encryptedstring = StringCipher.Encrypt(plaintext, password);

我喜欢那个类,因为如果我用相同的数据重复最后一行,它会给我不同的加密结果。

但是现在,我发现如果一个字符串有除base64字符以外的任何字符,它会引发这个异常: " 输入不是有效的Base-64字符串,因为它包含非基本64字符"我在网上搜索,我找到了很多这个问题的答案。像这样:

The input is not a valid Base-64 string as it contains a non-base 64 character

How can I solver an "base64 invalid characters" error?

在所有这些问题中,答案都是一样的:

  

从字符串中删除非base64字符!!!

但是,如果我或我的应用程序用户想要插入这样的字符串:" A @ S#D $?"或" CanYouGu3 $$我?"或....要加密?

我的问题:

A1。有没有办法解决上面的类问题(我在上面提到)而不替换或删除用户可能插入加密的任何字符?

A2。如果没有修复,那么其他最好的方法是什么?我可以使用什么方法它可以加密/解密任何包含其中任何字符的字符串。

PS:此代码也很好,对现有的非base64字符没有任何问题(因为它也使用此方法Encoding.UTF8.GetBytes来防止任何异常):https://codereview.stackexchange.com/questions/14892/simplified-secure-encryption-of-a-string

感谢您的时间

1 个答案:

答案 0 :(得分:3)

将输入字符串转换为字节数组,然后将其转换为base64。现在您的输入字符串是有效的base64,仍然可以加密。

byte[] data = Encoding.UTF8.GetBytes(inputString);
string b64 = Convert.ToBase64String(data);

您可能需要投入一些时间来了解为什么需要base64。加密算法在字节数组,原始数据而不是字符串上运行。