在 .NET C# 中存储加密密钥的最佳方式

在 .NET C# 中存储加密密钥的最佳方式

问题描述:

在我们的应用程序中,我们有很多敏感的配置设置,我们将它们存储在一个再次加密的 xml 文件中.

In our application we have a lot of sensitive configuration settings, which we are storing in a xml file which is again encrypted.

必须在运行时解密此安全文件并读取配置值.但是出现了一个问题,即密钥和初始化向量在代码中是硬编码的,因此任何人都可以使用 Reflector 读取它.

This secure file has to be decrypted in runtime and the configuration values read. but an issue arises that the key and initialization vector is hardcoded in the code and hence anyone can read it using Reflector.

在 .NET 中存储加密密钥以便没有人可以使用 Reflector 读取它们的最佳方法是什么?

What is the best way to store encryption keys in .NET so no one can read them using Reflector?

如果您想保护您的数据免受其他用户的侵害.查看 ProtectedData 类.

If you want to protect your data from other users. Take a look at the ProtectedData class.

(免责声明:此答案未涵盖保护您的数据以创建复制保护方案).

(Disclaimer: Protecting your data to create a copy protection scheme is not covered in this answer).

此类使用来自 Windows 的 DPAPI,在用户或机器级别加密和解密数据.

This classes uses the DPAPI from Windows, to encrypt and decrypt data on user or machine level.

使用 ProtectedData/DPAPI 使您无需自己处理密钥和保护数据.您可以选择保护当前用户的数据.相同域用户可以从不同计算机读取数据.

Using ProtectedData/DPAPI frees you from handling keys and securing the data yourself. And you can choose to protect the data for the current user. The data can be read from different computers, by the same domain users.

如果您想创建自己的密钥.您可以为每个用户/机器创建一个密钥,并将此密钥存储在注册表中.因为可以保护注册表,所以只有当前用户可以读回密钥.我知道注册表有坏处,但实际上非常擅长存储这样的数据.

If you want create your own key. You can create a key per user/machine, and store this key in the registry. Because the registry can be secured, only the current user can read the key back. I know the registry has bad karma, but is actually very good at storing data like this.

PS:不要把 IV 放在你的代码中.每次都新建一个IV,放在数据前面.

PS: Do not put the IV in your code. Create a new IV every time, and put it in front of the data.