如何加密可能有非基本64个字符的字符串 [英] How to encrypt strings that may have non-base 64 characters
问题描述
UPDATED:问题是我!我做了一个错误,否则两个Cods(下面和一个在 PS 是正确的)但仍然感谢@Luke Park的很好的答案,我学到了新的东西。
UPDATED: The problem was me! I did a mistake otherwise both Cods (below and the one at PS are correct) But still thanks to great answer from @Luke Park that I learned something new.
我不熟悉加密/解密算法,因此我搜索网络并发现这个类:
I am not familiar with encryption/decryption algorithms, Therefor I search the net and found this class:
代码是:
(我在解密中添加了一个Try / Catch
方法,如果密码错误,它将 return;
)
the code is :
(I add a Try/Catch in Decrypt
method in case the password was wrong it will 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;
}
}
}
我在我的应用程序如下:
I used that class at my application like this:
string plaintext = "InsertedPasswordByUserToEncrypt";
string password = plaintext; // use its own password as encryption key
string encryptedstring = StringCipher.Encrypt(plaintext, password);
如果我重复最后一行使用相同的数据,我喜欢该类会给我不同的加密结果。
and I like that class be cause it give me different encryption results if I repeat last line with same data.
但是现在,我发现一个字符串是否有除base64字符之外的任何字符会引发这个异常:
输入不是一个有效的Base-64字符串,因为它包含一个非基本的64个字符我搜索网络,我发现这个问题的许多答案。像这些:
But now, I found out if a string have any characters other than base64 characters it would rise this exception: "The input is not a valid Base-64 string as it contains a non-base 64 character" I search the net and I found many answers to this problem. Like these:
输入不是有效的Base-64字符串,因为它包含非基本64个字符
在所有这些问题中,答案是一样的:
In all those questions, answers was the same:
从字符串中删除非base64字符!!!
Remove non-base64 characters from your string!!!
但是,如果我或我的应用程序用户想插入一个字符串如下所示: A @ S#D $?或 CanYouGu3 $$ Me?或....要加密?
But what if I or my application users wants to insert a string like this: "A@S#D$?" or "CanYouGu3$$Me?" or .... to be encrypted?
我的问题:
A1。有没有办法解决上述类问题(上面提到的),而不用替换或删除用户可能插入的任何字符来加密?
A1. Is there any way to solve the above Class problem (that I mention at above) without replacing or removing any characters that users may insert to be encrypted?
A2。如果有没有修复,那么其他最好的方法是什么呢?我可以使用什么方法它可以加密/解密任何字符串中的任何字符。
A2. If there are no fix, So what are the other best ways? what method I can use that It can encrypt/decrypt any string with any characters in it.
PS:此代码也是一个很好的,没有任何问题现有非base64字符(因为它也使用此方法 Encoding.UTF8.GetBytes
来防止任何异常):https://codereview.stackexchange.com/questions/14892/simplified-secure-encryption-of-a-string
PS: This Code also is a good one and do not have any problem with existing non-base64 characters (cause it also use this method Encoding.UTF8.GetBytes
to prevent any exceptions): https://codereview.stackexchange.com/questions/14892/simplified-secure-encryption-of-a-string
感谢您的时间
推荐答案
将输入字符串转换为字节数组,然后将其转换为base64。现在你的输入字符串是有效的base64,仍然可以加密。
Convert your input string to a byte array and then convert that to base64. Now your input string is valid base64 and can still be encrypted.
byte[] data = Encoding.UTF8.GetBytes(inputString);
string b64 = Convert.ToBase64String(data);
您可能需要花一点时间了解为什么需要base64。加密算法在字节数组,原始数据,非字符串之间运行。
You might want to invest some time into understanding why base64 is required. Encryption algorithms operate over byte arrays, raw data, not strings.
这篇关于如何加密可能有非基本64个字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!