Wednesday 7 July, 2010

ENCRYPTING PASSWORDS AND OTHER SENSITIVE INFORMATION IN .NET

URL: http://msdn.microsoft.com/en-us/library/ms229741.aspx

If you want to serialize a password in some custom object you are working with, create another member that is the encrypted bytes and serialize/deserialize that.

For simply encrypting/decrypting a file, you can use System.IO.File.Encrypt/Decrypt.


  1. public static class Security
  2. {
  3. private static Encoding _encoding = Encoding.UTF8;
  4. private static byte[] _optionalEntropy = null;
  5. public static string Decrypt(this byte[] encryptedPassword)
  6. {
  7. if (encryptedPassword == null) throw new ArgumentNullException("encryptedPassword");
  8. byte[] bytes = ProtectedData.Unprotect(encryptedPassword, _optionalEntropy, DataProtectionScope.CurrentUser);
  9. return _encoding.GetString(bytes);
  10. }
  11. ///
  12. ///
  13. ///
  14. ///
  15. /// Empty collection if the input is null or empty.
  16. public static byte[] Encrypt(this string password)
  17. {
  18. if (string.IsNullOrEmpty(password)) return new byte[0];
  19. byte[] buffer = _encoding.GetBytes(password);
  20. return ProtectedData.Protect(buffer, _optionalEntropy, DataProtectionScope.CurrentUser);
  21. }
  22. }

No comments:

Post a Comment