Thursday, 25 September 2014

Symmetric encryption without using a key in the C# code

Either symmetric or Asymmetric encryptions, managing keys are a bigger problem than doing the encryption decryption itself. There is a way that we encrypt the data using key in the scope of the machine or user.

Following is the code

// To Encrypt
var textToSecure = "This is the text that we need to secure with encryption";
var textBytes = Encoding.Unicode.GetBytes(textToSecure);
var encryptedText = ProtectedData.Protect(textBytes, null, DataProtectionScope.CurrentUser);
// To Decrypt
var decryptedBytes= ProtectedData.Unprotect(encryptedText, null, DataProtectionScope.CurrentUser);
var decryptedText = Encoding.Unicode.GetString(decryptedBytes);

Note that as the 2nd Param we can pass in an additional byte array as an additional entropy.
 
Eg : static byte[] s_aditionalEntropy = { 9, 8, 7, 6, 5 };

DataProtectionScope can be either user or Machine. If we select the machine level scope anyone who has the access to the machine can decrypt the encrypted data.
 
 

No comments:

Post a Comment