我有一个Byte []字段,它是我需要加密的文件内容。没有什么特别的或花哨的,只是足以确保下一个获得它的人将无法轻易解码它。我会使用.Net Framework 4.0附带的加密,但我绝对不需要使文件比它更大。
我想过只是简单地反转数组或在末尾添加几个字节......?
如果我可以避免使阵列变得更大,那就太棒了。
有什么建议吗?
谢谢!
答案 0 :(得分:12)
1-16个字节的添加是否有害?默认情况下,AES将使用以下方法填充:
private static void EncryptThenDecrypt()
{
byte[] message; // fill with your bytes
byte[] encMessage; // the encrypted bytes
byte[] decMessage; // the decrypted bytes - s/b same as message
byte[] key;
byte[] iv;
using (var rijndael = new RijndaelManaged())
{
rijndael.GenerateKey();
rijndael.GenerateIV();
key = rijndael.Key;
iv = rijndael.IV;
encMessage = EncryptBytes(rijndael, message);
}
using (var rijndael = new RijndaelManaged())
{
rijndael.Key = key;
rijndael.IV = iv;
decMessage = DecryptBytes(rijndael, encMessage);
}
}
private static byte[] EncryptBytes(
SymmetricAlgorithm alg,
byte[] message)
{
if ((message == null) || (message.Length == 0))
{
return message;
}
if (alg == null)
{
throw new ArgumentNullException("alg");
}
using (var stream = new MemoryStream())
using (var encryptor = alg.CreateEncryptor())
using (var 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 == null) || (message.Length == 0))
{
return message;
}
if (alg == null)
{
throw new ArgumentNullException("alg");
}
using (var stream = new MemoryStream())
using (var decryptor = alg.CreateDecryptor())
using (var encrypt = new CryptoStream(stream, decryptor, CryptoStreamMode.Write))
{
encrypt.Write(message, 0, message.Length);
encrypt.FlushFinalBlock();
return stream.ToArray();
}
}
答案 1 :(得分:2)
不要发明自己的加密机制(即通过混淆安全),使用classes provided by the framework之一。