0

我正在编写一个 asp.net 应用程序,它加密敏感数据,这些数据由在同一域中不同用户帐户上运行的另一个 asp.net 应用程序解密。

我读过很多文章说使用 DPAPI 将密钥管理传递给操作系统级别。

在这种情况下如何使用 DPAPI?我不想将加密密钥存储在文件或数据库中。

4

1 回答 1

0

您需要参考 System.Security,并拥有与此类似的代码(它是 VB.NET,但很容易移植到 C#):

Imports System.Security.Cryptography 

' ....

Dim sensitiveDataBytes() As Byte = Encoding.Unicode.GetBytes(sensitiveData)
Dim entropy As Byte() = Guid.NewGuid().ToByteArray()
Dim encryptedSensitiveDataBytes() As Byte = ProtectedData.Protect(sensitiveDataBytes, entropy, DataProtectionScope.LocalMachine)
Dim entropyPlusSensitiveData As Byte() = entropy.Concat(encryptedSensitiveDataBytes).ToArray()

Return entropyPlusSensitiveData

您在这里所做的是System.Security.Cryptography.ProtectedData使用 DPAPI 来保护具有“本地计算机”范围的数据,然后创建一些随机的 16 字节熵,将其添加到加密数据之前。然后您可以安全地传递 16+(加密数据长度)大小的数组。

在解密方面,你做了一个类似的技巧:你去掉 16 个熵字节,然后使用 DPAPI 解密:

Dim entropyPlusSensitiveData As Byte() = data ' the byte array created previously
Dim entropy() As Byte = entropyPlusSensitiveData.Take(16).ToArray()
Dim encryptedSensitiveDataBytes() As Byte = entropyPlusSensitiveData.Skip(16).ToArray()
Dim sensitiveDataBytes() As Byte = ProtectedData.Unprotect(encryptedSensitiveDataBytes, entropy, DataProtectionScope.LocalMachine)

熵不是严格要求的,但强烈推荐。

于 2011-02-11T10:14:47.983 回答