我正在尝试使用AES 256 ECB编码一个字符串,并使用.Net的System.Security.Cryptography库对零填充,但是结果不是我所期望的。
我正在使用与this test case相匹配的my reciver's code进行测试。
我的代码如下:
public static class Util
{
public static byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
private static readonly byte[] KEY = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
private static readonly byte[] IV = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
public static byte[] Encrypt(string original)
{
byte[] encrypted;
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Padding = PaddingMode.Zeros;
aesAlg.Mode = CipherMode.ECB;
aesAlg.KeySize = 256;
// Create the streams used for encryption.
using (ICryptoTransform encryptor = aesAlg.CreateEncryptor(KEY, IV))
using (MemoryStream msEncrypt = new MemoryStream())
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
var bytes = Encoding.ASCII.GetBytes(original);
swEncrypt.Write(bytes);
}
encrypted = msEncrypt.ToArray();
}
}
return encrypted;
}
}
然后,这是我的测试用例正在失败,十六进制的结果数组是05212CB5430653FA4BD2253D20353903,而不是9798D10A63E4E167122C4C07AF49C3A9。
public void TesEncrypt()
{
var array = Util.Encrypt("text to encrypt");
var expected = Util.StringToByteArray("9798D10A63E4E167122C4C07AF49C3A9");
CollectionAssert.AreEqual(expected, array);
}
答案 0 :(得分:1)
此:
//Write all data to the stream.
var bytes = Encoding.ASCII.GetBytes(original);
swEncrypt.Write(bytes);
应该是
//Write all data to the stream.
swEncrypt.Write(original);
StreamWriter已经负责将您的字符串序列化为字节数组。
Here's a working fiddle.(我那里没有Assert.AreEqual,但是前两个字节与您的预期输出匹配。哦,顺便说一下,Assert.AreEqual is wrong here,您应该使用{{1 }}。
我发现此错误的原因是,您的原始代码返回了相同的输出,而与输入无关。发生的情况是调用了TextWriter.Write(object) overload,它会在您的字节数组上调用CollectionAssert.AreEqual
(产生字符串ToString
)并对该字符串(而不是您的输入字符串)进行加密。