Encrypting passwords and other sensitive information in .NET


/ Published in: C#
Save to your folder(s)

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](http://msdn.microsoft.com/en-us/library/system.io.file.encrypt.aspx)/Decrypt.


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

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.