我正在使用Framework的对象编写一个用于加密/解密的简单库。方法如下:
public static byte[] Encrypt(byte[] key, byte[] vector, byte[] input)
{
if(key.Length == 0)
throw new ArgumentException("Cannot encrypt with empty key");
if (vector.Length == 0)
throw new ArgumentException("Cannot encrypt with empty vector");
if (input.Length == 0)
throw new ArgumentException("Cannot encrypt empty input");
var unencryptedBytes = input;
using(AesCryptoServiceProvider aes = new AesCryptoServiceProvider {Key = key, IV = vector})
using(ICryptoTransform encryptor = aes.CreateEncryptor())
using (MemoryStream ms = new MemoryStream())
using (CryptoStream writer = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
writer.Write(unencryptedBytes, 0, unencryptedBytes.Length);
writer.FlushFinalBlock();
var byteArray = ms.ToArray();
if(byteArray.Length == 0)
throw new Exception("Attempted to encrypt but encryption resulted in a byte array of 0 length.");
return byteArray;
}
}
public static byte[] Decrypt(byte[] key, byte[] vector, byte[] encrypted)
{
if (key.Length == 0)
throw new ArgumentException("Cannot encrypt with empty key");
if (vector.Length == 0)
throw new ArgumentException("Cannot encrypt with empty vector");
if (encrypted == null || encrypted.Length == 0)
throw new ArgumentException("Cannot decrypt empty or null byte array");
byte[] unencrypted;
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider { Key = key, IV = vector })
using (ICryptoTransform decryptor = aes.CreateDecryptor(key, vector))
using (MemoryStream ms = new MemoryStream(encrypted))
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
cs.Read(encrypted, 0, encrypted.Length);
unencrypted = ms.ToArray();
}
return unencrypted;
}
以编码字符串形式提供它,例如,如下所示:
var expected = "This is an example message";
var messageBytes = Encoding.UTF8.GetBytes(expected);
进入(在此示例中)26个字节。加密后它会留下32个字节,当它被转换回字符串时,它在末尾附加了随机字符,但在其他方面完全有效,如下所示:
"This is an example message�(4���"
生成新的向量/键会更改附加到末尾的随机字符。
如何消除这种额外的字节行为?
修改
包括要求的单元测试。
[TestMethod]
public void CanEncryptAndDecryptByteArray()
{
var expected = "This is an example message";
var messageBytes = Encoding.UTF8.GetBytes(expected);
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.GenerateIV();
aes.GenerateKey();
var byteKey = Convert.ToBase64String(aes.Key);
var vectorKey = Convert.ToBase64String(aes.IV);
var key = Convert.FromBase64String("Qcf+3VzYNAfPUCfBO/ePSxCLBLItkVfk8ajK86KYebs=");
var vector = Convert.FromBase64String("aJNKWP7M2D44jilby6BzGg==");
var encrypted = EncryptionManager.Encrypt(key, vector, messageBytes);
var decrypted = EncryptionManager.Decrypt(key, vector, encrypted);
var actual = Encoding.UTF8.GetString(decrypted);
Assert.AreEqual(expected, actual);
}
答案 0 :(得分:3)
垃圾字节是因为我们正在读取和写入同一个数组。
new MemoryStream(encrypted))
告诉地穴读取encrypted
。
cs.Read(encrypted, 0, encrypted.Length);
告诉它写信给encrypted
。
解决方案:
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider { Key = key, IV = vector })
using (ICryptoTransform decryptor = aes.CreateDecryptor(key, vector))
using (MemoryStream ms = new MemoryStream(encrypted))
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
var decrypted = new byte[encrypted.Length];
var bytesRead = cs.Read(decrypted, 0, encrypted.Length);
return decrypted.Take(bytesRead).ToArray();
}
请注意,我们从数组中获取bytesRead
,而不是完整数组,因为我们最终会得到空字节(无法进行字符串比较,但在编辑器中看起来相同)
答案 1 :(得分:1)
AES加密是block encryption,块大小为16字节(128位)[注意:密钥大小可以是128位,192位或256位,但数据块大小是乘以16字节]。因此,要使用AES,生成的加密消息将是16的乘法 - 否则不能。
要解密它,你可能想要摆脱它引起的额外字节。
执行此操作的一种方法是在邮件中附加标题,说明邮件的字节数。然后在解密端,您读取此标头并减少字节数
[header = value of 26] + [message]
或者,您可以在加密消息的末尾添加一些额外的字节
[message][append with 000000] //to make up the block, such that the message length will be of multiplication of 16
在上述两种方法中,我个人更喜欢第一种方法,因为它更清晰,而第二种方法假设您收到某些文本模式,最终无法连接0000。
除了以上两种方式之外,我不知道是否有办法解决这个问题 - 隐含地(例如使用CryptoStream)或明确地。
答案 2 :(得分:1)
AES加密在16,24或32字节(或128,192或256位)块中进行加密。所以你得到的数据只是随机数据打包到最后。
您必须使用几个字节前置数据来表示实际的数据:
var length = new byte [] { (byte) ((unencryptedBytes.Length >> 8) & 0xff) ,
(byte) (unencryptedBytes.Length & 0xff);
writer.Write(length, 0, length.Length);
writer.Write(unencryptedBytes, 0, unencryptedBytes.Length);
writer.FlushFinalBlock();
然后在读者中检索长度:
unencrypted = ms.ToArray();
int length = ((int) unencrypted[0] << 8) + unencrypted[1];
var result = new byte[length];
unencrypted.CopyTo(result, 2, 0, length);
return result;