到目前为止,我发现的很多项目都有些模糊或……不具体,所以我希望能得到答案。
我有两个小方法 - 看起来像这样的简单方法......
private const string initVector = "1234567890123456";
private const string SaltValue = "ThisIsMySaltValue";
private const int KeySize = 256;
public static string Encrypt(string textToEncrypt)
{
var rijndael = new RijndaelManaged {KeySize = KeySize};
var salt = SaltValue.ToByteArray();
var vector = initVector.ToByteArray();
var rfcBytes = new Rfc2898DeriveBytes(vector, salt, 2);
var key = rfcBytes.GetBytes(rijndael.KeySize/8);
ICryptoTransform encrypt = rijndael.CreateEncryptor(key, vector);
var stream = new MemoryStream();
var data = Encoding.ASCII.GetBytes(textToEncrypt);
stream.Write(data, 0, data.Length);
var cryptoStream = new CryptoStream(stream, encrypt, CryptoStreamMode.Write);
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
cryptoStream.Close();
return Convert.ToBase64String(stream.ToArray());
}
public static string Decrypt(string textToDecrypt)
{
var vector = initVector.ToByteArray();
var salt = SaltValue.ToByteArray();
var encrypted = textToDecrypt.ToByteArray();
var rijndael = new RijndaelManaged {KeySize = KeySize};
var rfcBytes = new Rfc2898DeriveBytes(vector, salt, 2);
var key = rfcBytes.GetBytes(rijndael.KeySize/8);
var decrypt = rijndael.CreateDecryptor(key, vector);
var stream = new MemoryStream(encrypted);
var cryptoStream = new CryptoStream(stream, decrypt, CryptoStreamMode.Read);
byte[] plainBytes = new byte[textToDecrypt.Length];
var decryptedLength = cryptoStream.Read(plainBytes, 0, plainBytes.Length);
var plainText = Encoding.UTF8.GetString(plainBytes, 0, decryptedLength);
return plainText;
}
单元测试看起来像这样......
[Test]
public void JustTestingThisOut()
{
var encryptMe = "SomethingToEncrypt";
string result = encryptMe.ConvertToEncrypted();
result.ShouldNotEqual(encryptMe);
string backToReadAble = result.ConvertToDecrpted();
backToReadAble.ShouldEqual(encryptMe);
}
ToByteArray 只是返回 Encoding.UTF8.GetBytes(toByte); 我的测试字符串很简单——“SomethingToEncrypt”。我已经陷入困境,发现这种想法可能是问题(Convert.ToBase64String 和 Convert.FromBase64String),似乎没有任何区别。至于错误...
TestCase 'Tests.Encryption.EncryptionUnitTests.JustTestingThisOut' 失败:System.Security.Cryptography.CryptographicException:要解密的数据长度无效。在 System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(字节 [] inputBuffer,Int32 inputOffset,Int32 inputCount)
我有 FlushFinalBlock() 在那里,我认为可以这样做,但是......不,也没有区别。有任何想法吗?要尝试的东西?