简体   繁体   English

对文件使用ProtectedData.Protect()

[英]Using ProtectedData.Protect() for files

I'm working on some code that ideally can encrypt a file using the Windows DPAPI. 我正在研究一些可以理想地使用Windows DPAPI加密文件的代码。 This is fine if the file can be read directly into memory, but if it can't I cannot encrypt it. 如果可以将文件直接读取到内存中,这很好,但是如果不能,则无法对其进行加密。 ProtectedData.Protect takes 3 arguments - the data as a byte array, optional entropy as a byte array, and a scope. ProtectedData.Protect接受3个参数-数据作为字节数组,可选的熵作为字节数组,以及范围。

When I use it as below, it yields 2 different results: 当我按如下方式使用它时,它会产生2种不同的结果:

var data = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};

byte[] encryptedDataA = ProtectedData.Protect(data, null, DataProtectionScope.CurrentUser);

byte[] encryptedDataB = ProtectedData.Protect(data, null, DataProtectionScope.CurrentUser);

Console.WriteLine(encryptedDataA.SequenceEqual(encryptedDataB));

// False!!!!

Specifying identical entropy also results in different results. 指定相同的熵也会导致不同的结果。 Here is an MSDN answer corroborating this. 是MSDN的佐证。 However, there is no documentation I can find detailing the header or how to read it. 但是,没有任何文档可以找到有关标题或如何读取它的详细信息。

As there are no overloads taking it as anything but a byte[] , I can't find anyway of fixing this to allow for encryption of large files without ugly chunking of the data. 由于除了byte[]以外没有其他重载,因此无论如何我都找不到解决此问题的方法,以允许对大文件进行加密而又不会对数据进行难看的分块。

Is there any way to work around this? 有什么办法可以解决此问题?

If you look at the source code for ProtectedData.Protect , you will find that at some point it redirects the call to the Crypt32 library: CryptProtectData function . 如果查看ProtectedData.Protect源代码 ,您会发现在某个时候它将调用重定向到Crypt32库: CryptProtectData函数

In the Remarks section, you will see: 在“ 备注”部分,您将看到:

The function creates a session key to perform the encryption. 该函数创建一个会话密钥以执行加密。 The session key is derived again when the data is to be decrypted. 当要解密数据时,再次导出会话密钥。

This, to me, it reads like a new key is generated every time the function is called. 对我来说,这就像每次调用该函数时都会生成一个新密钥一样。

So, if you need to get the same value every time, you'd be better off using AES instead. 因此,如果您每次都需要获得相同的值,则最好使用AES。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM