2011-02-11 146 views
0

我正在编写一个asp.net应用程序,用于加密由另一个在同一个域中的不同用户帐户上运行的asp.net应用程序解密的敏感数据。使用DPAPI安全加密密钥

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

如何在此场景中使用DPAPI?我不想将加密密钥存储在文件或数据库中。

回答

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) 

熵没有严格要求,但强烈建议。