07.11.2014 Views

Enterprise Library Test Guide - Willy .Net

Enterprise Library Test Guide - Willy .Net

Enterprise Library Test Guide - Willy .Net

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

146<br />

<strong>Enterprise</strong> <strong>Library</strong> <strong>Test</strong> <strong>Guide</strong><br />

Check<br />

Yes<br />

Description<br />

Use DPAPI to encrypt configuration secrets so as to eliminate the key management<br />

issue. (DPAPI uses the password of the user account associated with the code that<br />

calls the DPAPI functions in order to derive the encryption key. As a result, the operating<br />

system, and not the application, manages the key.) The Cryptography Application<br />

Block uses DPAPI to encrypt the key. It retrieves the key from the key file or cache each<br />

time it must encrypt or decrypt information. The following code example shows how the<br />

Cryptography Application Block stores and retrieves the key.<br />

public static ProtectedKey Read(string protectedKeyFileName, DataProtectionScope<br />

dpapiProtectionScope)<br />

{<br />

string completeFileName =<br />

Path.GetFullPath(protectedKeyFileName);<br />

if (cache[completeFileName] != null) return<br />

cache[completeFileName];<br />

using (FileStream stream = new<br />

FileStream(protectedKeyFileName, FileMode.Open,<br />

FileAccess.Read, FileShare.Read))<br />

{<br />

ProtectedKey protectedKey = Read(stream,<br />

dpapiProtectionScope);<br />

cache[completeFileName] = protectedKey;<br />

return protectedKey;<br />

}<br />

}<br />

The following code example shows how to use DPAPI to decrypt the key.<br />

public byte[] Encrypt(byte[] plaintext)<br />

{<br />

byte[] output = null;<br />

byte[] cipherText = null;<br />

this.algorithm.Key = Key;<br />

private byte[] Key<br />

{<br />

get<br />

{<br />

return key.DecryptedKey;<br />

}<br />

}<br />

}<br />

public byte[] DecryptedKey<br />

{<br />

get { return Unprotect(); }<br />

}<br />

public virtual byte[] Unprotect()<br />

{<br />

return ProtectedData.Unprotect(protectedKey, null,<br />

protectionScope);<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!