如何加密可能包含非 base 64 字符的字符串
How to encrypt strings that may have non-base 64 characters
更新:问题是 我!我犯了一个错误,否则两个 Cods(下面和 PS 的那个都是正确的)但是仍然感谢@Luke Park 的出色回答,我学到了一些新东西。
我不熟悉encryption/decryption算法,所以我在网上搜索发现这个class:
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;
}
}
}
我在我的申请中这样使用 class:
string plaintext = "InsertedPasswordByUserToEncrypt";
string password = plaintext; // use its own password as encryption key
string encryptedstring = StringCipher.Encrypt(plaintext, password);
我喜欢 class 因为如果我用相同的数据重复最后一行,它会给我不同的加密结果。
但是现在,我发现如果一个字符串有除 base64 字符之外的任何字符,它会引发这个异常:
“输入不是有效的 Base-64 字符串,因为它包含非 base-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?
在所有这些问题中,答案都是一样的:
Remove non-base64 characters from your string!!!
但是如果我或我的应用程序用户想要插入这样的字符串怎么办:“A@S#D$?”或“CanYouGu3$$我?" 或 .... 要加密?
我的问题:
A1. 有什么方法可以解决上述 Class 问题(我在上面提到过)而不用替换或删除用户可能插入的任何字符加密?
A2.如果没有修复,那么还有什么好的方法呢?我可以使用什么方法它可以 encrypt/decrypt 任何包含任何字符的字符串。
PS:这段代码也很好,对现有的非 base64 字符没有任何问题(因为它也使用这种方法 Encoding.UTF8.GetBytes
来防止任何异常):https://codereview.stackexchange.com/questions/14892/simplified-secure-encryption-of-a-string
感谢您的宝贵时间
将您的输入字符串转换为字节数组,然后将其转换为 base64。现在您的输入字符串是有效的 base64 并且仍然可以被加密。
byte[] data = Encoding.UTF8.GetBytes(inputString);
string b64 = Convert.ToBase64String(data);
您可能需要花一些时间来理解为什么需要 base64。加密算法对字节数组、原始数据而非字符串进行操作。
更新:问题是 我!我犯了一个错误,否则两个 Cods(下面和 PS 的那个都是正确的)但是仍然感谢@Luke Park 的出色回答,我学到了一些新东西。
我不熟悉encryption/decryption算法,所以我在网上搜索发现这个class:
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;
}
}
}
我在我的申请中这样使用 class:
string plaintext = "InsertedPasswordByUserToEncrypt";
string password = plaintext; // use its own password as encryption key
string encryptedstring = StringCipher.Encrypt(plaintext, password);
我喜欢 class 因为如果我用相同的数据重复最后一行,它会给我不同的加密结果。
但是现在,我发现如果一个字符串有除 base64 字符之外的任何字符,它会引发这个异常: “输入不是有效的 Base-64 字符串,因为它包含非 base-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?
在所有这些问题中,答案都是一样的:
Remove non-base64 characters from your string!!!
但是如果我或我的应用程序用户想要插入这样的字符串怎么办:“A@S#D$?”或“CanYouGu3$$我?" 或 .... 要加密?
我的问题:
A1. 有什么方法可以解决上述 Class 问题(我在上面提到过)而不用替换或删除用户可能插入的任何字符加密?
A2.如果没有修复,那么还有什么好的方法呢?我可以使用什么方法它可以 encrypt/decrypt 任何包含任何字符的字符串。
PS:这段代码也很好,对现有的非 base64 字符没有任何问题(因为它也使用这种方法 Encoding.UTF8.GetBytes
来防止任何异常):https://codereview.stackexchange.com/questions/14892/simplified-secure-encryption-of-a-string
感谢您的宝贵时间
将您的输入字符串转换为字节数组,然后将其转换为 base64。现在您的输入字符串是有效的 base64 并且仍然可以被加密。
byte[] data = Encoding.UTF8.GetBytes(inputString);
string b64 = Convert.ToBase64String(data);
您可能需要花一些时间来理解为什么需要 base64。加密算法对字节数组、原始数据而非字符串进行操作。