我正在try 在中实现一些数据加密.NET提供的密码.据我所知,我用一个对称密钥加密文件,并用用户生成的另一个密钥加密该密钥.这意味着密码更改不需要更改数据,只需更新加密密钥即可.
在测试AES函数时,我可以加密我的256位密钥,但在解密时,我只能从中获得前16个字节.净值:
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.
}
在这里,pwdK1
实际上是使用第三方Argon2
库生成的,这篇文章修改了代码.
使用的密钥和IV相同,模式相同,但在解密阶段读取解密的密钥时,我只看到存储在变量p
中的Key
中的前16个字节.对于前crypStr.Read
,我返回了完整的32个字节,但解密读取只返回I中的16个字节.其余16个字节都是0.
你知道我做错了什么吗?