I'm attempting to implement some encryption of data in .NET with a user supplied password. As I understand this, I encrypt the file with a symetric key, and encrypt this key with another key that is generated by the user. This means that a password change does not require a change to the data, just an update to the encrypted key.
When testing out the AES functions, I can encrypt my 256 bit key, but when decrypting I only get the first 16 bytes back from .NET:
public static byte[] Salt = new byte[64];
public static byte[] IV = new byte[16];
public static string Password1 = "PWD";
public static byte[] Key = new byte[32];
static void Main(string[] args)
{
Salt = RandomNumberGenerator.GetBytes(64);
IV = RandomNumberGenerator.GetBytes(16);
Key = RandomNumberGenerator.GetBytes(32);
var pwdK1 = RandomNumberGenerator.GetBytes(32);
byte[] aKey1 = new byte[32];
byte[] bKey1 = new byte[32];
using (Aes aes = Aes.Create())
{
aes.Mode = CipherMode.CBC;
aes.Key = pwdK1; //use key generated by user pwd
aes.IV = IV;
var str = new MemoryStream(Key);
using (var crypStr = new CryptoStream(str, aes.CreateEncryptor(), CryptoStreamMode.Read))
{
int i = crypStr.Read(aKey1, 0, 32);
}
}
using (Aes aes = Aes.Create())
{
aes.Mode = CipherMode.CBC;
aes.Key = pwdK1; //use key generated by user pwd
aes.IV = IV;
var str = new MemoryStream(aKey1);
using (var crypStr = new CryptoStream(str, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
int i = crypStr.Read(bKey1, 0, 32);
var p = bKey1.ToArray();
}
}
//we should have Key in p/bKey1, but we only have the first 16 bytes of Key.
}
Here, pwdK1
is actually generated using a 3rd party Argon2
library, code modified for this post.
The key and IV used are the same, the mode is the same, but when reading out the decrypted key in the decrypt stage, I only see the first 16 bytes that I see in Key
stored in variable p
. For the first crypStr.Read
I get a full 32 bytes returned, but the decrypt Read returns only 16 bytes in i. The remaining 16 bytes are all 0.
Any ideas what I could be doing wrong?