MRK*_*MRK 0 .net c# encryption base64 winforms
更新:问题是我!我犯了一个错误,否则两个 Cods(下面和PS上的那个都是正确的)但仍然感谢 @Luke Park 的精彩回答,我学到了一些新东西。
我对加密/解密算法不熟悉,因此我在网上搜索并找到了这个类:
代码是:(我在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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在我的应用程序中使用了该类,如下所示:
string plaintext = "InsertedPasswordByUserToEncrypt";
string password = plaintext; // use its own password as encryption key
string encryptedstring = StringCipher.Encrypt(plaintext, password);
Run Code Online (Sandbox Code Playgroud)
我喜欢这个类,因为如果我用相同的数据重复最后一行,它会给我不同的加密结果。
但现在,我发现如果一个字符串包含除 Base64 字符以外的任何字符,则会出现此异常:“输入不是有效的 Base-64 字符串,因为它包含非 Base 64 字符”我在网上搜索,发现这个问题有很多答案。像这些:
输入不是有效的 Base-64 字符串,因为它包含非 Base-64 字符
所有这些问题的答案都是一样的:
从字符串中删除非 Base64 字符!!!
但是,如果我或我的应用程序用户想要插入这样的字符串:“ A@S#D$? ”或“ CanYouGu3$$Me? ”或......进行加密,该怎么办?
我的问题:
A1。有没有办法解决上述类问题(我在上面提到的)而不替换或删除用户可能插入加密的任何字符?
A2。如果没有解决办法,那么其他最好的方法是什么?我可以使用什么方法它可以加密/解密其中包含任何字符的任何字符串。
PS:此代码也是一个很好的代码,对现有的非 Base64 字符没有任何问题(因为它也使用此方法Encoding.UTF8.GetBytes来防止任何异常): https: //codereview.stackexchange.com/questions/14892/simplified-字符串的安全加密
谢谢你的时间
将输入字符串转换为字节数组,然后将其转换为 base64。现在您的输入字符串是有效的 base64,并且仍然可以加密。
byte[] data = Encoding.UTF8.GetBytes(inputString);
string b64 = Convert.ToBase64String(data);
Run Code Online (Sandbox Code Playgroud)
您可能需要花一些时间来理解为什么需要 Base64。加密算法对字节数组、原始数据而不是字符串进行操作。
| 归档时间: |
|
| 查看次数: |
6804 次 |
| 最近记录: |