Reputation: 1301
I want to use the AES algorithm to encrypt some files. This is my code to create a Random key:
public byte[] CreateRandomKey()
{
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 256;
aes.BlockSize = 128;
aes.GenerateKey();
return aes.Key;
}
First thing I want to know is, whether the GenerateKey() Method is "random enough" to be secure?
This is my code for en- and decryption:
public byte[] Encrypt(byte[] key, byte[] input)
{
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 256;
aes.BlockSize = 128;
aes.Key = key;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(input, 0, input.Length);
cs.Close();
return ms.ToArray();
}
public byte[] Decrypt(byte[] key, byte[] input)
{
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 256;
aes.BlockSize = 128;
aes.Key = key;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(input, 0, input.Length);
cs.Close();
return ms.ToArray();
}
I would like to know if the algorithm is secure without an initialization vector? And I've got a problem with the algorithm, if I encrypt some bytes and decrypt the result of the encryption, the result is different from the original bytes. I hope that isn't to much for one question and someone can help me.
Upvotes: 0
Views: 108
Reputation: 93948
Yes, the key generation should be secure. The OS probably has the best access to a cryptographically secure random number generator. This is not a full security review of course.
You are using a random IV because .NET automatically generates one for you. Problem is that you don't communicate that IV to the decrypt function. This is why the decryption of the first 16 bytes of ciphertext will fail.
Upvotes: 2