AesEncryption似乎无法解密吗? [英] AesEncryption doesn't appear to decrypt right?
问题描述
我编写了此类,以允许我加密和解密对象的json表示形式,但它似乎不能作为MSDN文档使用(此处: https://msdn.microsoft.com/zh-我们/library/system.security.cryptography.aesmanaged%28v=vs.95%29.aspx?f=255&MSPPError=-2147217396 )建议它应该...
I wrote this class to allow me to encrypt and decrypt the json representation of objects but it doesn't appear to work as the MSDN documentation (here: https://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged%28v=vs.95%29.aspx?f=255&MSPPError=-2147217396) suggests it should ...
using Newtonsoft.Json;
using System;
using System.Configuration;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web.Configuration;
namespace Core.Data
{
public class AesCrypto<T> : ICrypto<T>
{
string DecryptionKey { get { return ((MachineKeySection)ConfigurationManager.GetSection("system.web/machineKey")).DecryptionKey; } }
public string Encrypt(T source, string salt)
{
var sourceString = JsonConvert.SerializeObject(source);
using (var aes = new AesManaged())
{
aes.Padding = PaddingMode.PKCS7;
aes.GenerateIV();
using (var stream = new MemoryStream())
{
var deriveBytes = new Rfc2898DeriveBytes(DecryptionKey, Encoding.Unicode.GetBytes(salt));
aes.Key = deriveBytes.GetBytes(128 / 8);
stream.Write(BitConverter.GetBytes(aes.IV.Length), 0, sizeof(int));
stream.Write(aes.IV, 0, aes.IV.Length);
using (var cs = new CryptoStream(stream, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] rawPlaintext = Encoding.Unicode.GetBytes(sourceString);
cs.Write(rawPlaintext, 0, rawPlaintext.Length);
cs.FlushFinalBlock();
stream.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(stream, Encoding.Unicode))
return reader.ReadToEnd();
}
}
}
}
public T Decrypt(string sourceString, string salt)
{
using (Aes aes = new AesManaged())
{
aes.Padding = PaddingMode.PKCS7;
var deriveBytes = new Rfc2898DeriveBytes(DecryptionKey, Encoding.Unicode.GetBytes(salt));
aes.Key = deriveBytes.GetBytes(128 / 8);
using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(sourceString)))
{
stream.Seek(0, SeekOrigin.Begin);
// Get the initialization vector from the encrypted stream
aes.IV = ReadIV(stream);
using (var reader = new StreamReader(new CryptoStream(stream, aes.CreateDecryptor(aes.Key, aes.IV), CryptoStreamMode.Read), Encoding.Unicode))
{
var resultString = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(resultString);
}
}
}
}
byte[] ReadIV(Stream s)
{
byte[] rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
}
byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
}
return buffer;
}
}
}
我编写了以下单元测试来测试此功能...
I wrote the following unit test to test this functionality out ...
using Core.Data;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Core.Tests
{
[TestClass]
public class CryptoTests
{
class EncryptableObject
{
public int Id { get; set; }
public string Name { get; set; }
public DateTimeOffset When { get; set; }
}
[TestMethod]
public void TestAesCrypto()
{
var testInput = new EncryptableObject { Id = 123, Name = "Victim", When = DateTimeOffset.UtcNow };
var crypto = new AesCrypto<EncryptableObject>();
var testSalt = "testtest";
var magicString = crypto.Encrypt(testInput, testSalt);
var testOutput = crypto.Decrypt(magicString, testSalt);
Assert.AreEqual(testInput.Id, testOutput.Id);
Assert.AreEqual(testInput.Name, testOutput.Name);
Assert.AreEqual(testInput.When, testOutput.When);
}
}
}
问题似乎无穷无尽。 ..
Problems seem to be endless ...
- 由于某种原因,我的json输出中的解密方法在读取 var resultString = reader.ReadToEnd();
- 每次运行时输出都不同。
- 当我不附加
调试器时,它会引发关于填充的异常,但是会在我不对json进行反序列化时引发异常。 - 不知道为什么它从错误的配置值中读取(但这可能与加密不起作用无关)
- For some reason I get what seems to be chineese characters in my json output in the decrypt method on the line that reads "var resultString = reader.ReadToEnd();"
- The output is different each time I run it.
- It throws an exception about padding when I don't attach the debugger, but throws an exception about failing to deserialise the json when I do.
- Not sure why it appears to be reading form the wrong config value (but that's likely unrelated to the encryption not working)
我在做什么错了?
推荐答案
好吧,我发现这基本上就是我的编码问题,因此,我进一步采取了这一措施,并在@ https://gist.github.com/jbtule/4336842#file-aesthenhmac-cs
Ok I figured out it was basically encoding that was my problem here, so taking this step further I went and grabbed the code from the examples by @jbtule (thanks James) over @ https://gist.github.com/jbtule/4336842#file-aesthenhmac-cs
已抓取了 AESThenHMAC然后我可以写这样的类……
Having grabbed the "AESThenHMAC" class I could then write this ...
public class AesCrypto<T> : ICrypto<T>
{
public string Encrypt(T source, string key)
{
var e = Encoding.UTF8;
var rawData = e.GetBytes(JsonConvert.SerializeObject(source));
var cipherData = AESThenHMAC.SimpleEncryptWithPassword(rawData, key);
return Convert.ToBase64String(cipherData);
}
public T Decrypt(string source, string key)
{
var e = Encoding.UTF8;
var decryptedBytes = AESThenHMAC.SimpleDecryptWithPassword(Convert.FromBase64String(source), key);
return JsonConvert.DeserializeObject<T>(e.GetString(decryptedBytes));
}
}
...完美地通过了上面的单元测试: )
... which passes the above unit test perfectly :)
这篇关于AesEncryption似乎无法解密吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!