2011-02-11 143 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) 

熵沒有嚴格要求,但強烈建議。