Secure Crypto keys using DPAPI

792 Views Asked by At

I am writing an asp.net application that encrypts sensitive data which is decrypted by another asp.net application running on different user accounts in the same domain.

I have read a lot of articles saying to use DPAPI to pass the key management to the OS level.

How can I use DPAPI in this scenario? i don't want to store the crypto key in a file or database.

1

There are 1 best solutions below

0
On

You need to reference System.Security, and have code similar to this (it's VB.NET but it's trivially ported to 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

What you're doing here is you're using System.Security.Cryptography.ProtectedData to use DPAPI in order to protect data with "local machine" scope, and then creating some random 16-bytes entropy, which you prepend to the encrypted data. Then you can pass safely the 16+(length of encrypted data)-sized array around.

On the decryption side you do a similar trick: you strip off the 16 entropy bytes and you then use DPAPI to decrypt:

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)

The entropy is not strictly required, but it's highly recommended.