我有一个 Byte[] 字段,它是我需要加密的文件内容。没有什么特别或奇特的,只是足以确保下一个得到它的人不费吹灰之力就无法轻松解码它。我会使用 .Net Framework 4.0 附带的加密,但我绝对不需要使文件比实际更大。
我想过只是简单地反转数组或在末尾添加几个字节......?
如果我可以避免使数组变得更大,那就太好了。
有什么建议么?
Thanks!
添加1-16字节有伤害吗? AES 默认情况下将使用以下方法进行填充:
private static void EncryptThenDecrypt(byte[] msg)
{
byte[] message = msg; // fill with your bytes
if (message is null)
{
return;
}
byte[] encMessage; // the encrypted bytes
byte[] decMessage; // the decrypted bytes - s/b same as message
byte[] key;
byte[] iv;
using (SymmetricAlgorithm aes = Aes.Create())
{
if (aes is null)
{
iv = key = null;
encMessage = Array.Empty<byte>();
}
else
{
aes.GenerateKey();
aes.GenerateIV();
key = aes.Key;
iv = aes.IV;
encMessage = EncryptBytes(aes, message);
}
}
using (SymmetricAlgorithm aes = Aes.Create())
{
if (aes is null || key is null)
{
decMessage = Array.Empty<byte>();
}
else
{
aes.Key = key;
aes.IV = iv;
decMessage = DecryptBytes(aes, encMessage);
}
}
Debug.Assert(message.SequenceEqual(decMessage), "Decrypted bytes do not match original bytes.");
}
private static byte[] EncryptBytes(SymmetricAlgorithm alg, byte[] message)
{
if (message is null)
{
#pragma warning disable S1168 // Empty arrays and collections should be returned instead of null
return null;
#pragma warning restore S1168 // Empty arrays and collections should be returned instead of null
}
if (message.Length == 0)
{
return message;
}
if (alg is null)
{
throw new ArgumentNullException(nameof(alg));
}
using (MemoryStream stream = new MemoryStream())
using (ICryptoTransform encryptor = alg.CreateEncryptor())
using (CryptoStream encrypt = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
{
encrypt.Write(message, 0, message.Length);
encrypt.FlushFinalBlock();
return stream.ToArray();
}
}
private static byte[] DecryptBytes(SymmetricAlgorithm alg, byte[] message)
{
if (message is null)
{
#pragma warning disable S1168 // Empty arrays and collections should be returned instead of null
return null;
#pragma warning restore S1168 // Empty arrays and collections should be returned instead of null
}
if (message.Length == 0)
{
return message;
}
if (alg is null)
{
throw new ArgumentNullException(nameof(alg));
}
using (MemoryStream stream = new MemoryStream())
using (ICryptoTransform decryptor = alg.CreateDecryptor())
using (CryptoStream encrypt = new CryptoStream(stream, decryptor, CryptoStreamMode.Write))
{
encrypt.Write(message, 0, message.Length);
encrypt.FlushFinalBlock();
return stream.ToArray();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)