Return to Snippet

Revision: 27413
at June 7, 2010 15:18 by pckujawa


Initial Code
public static class Security
{
    private static Encoding _encoding = Encoding.UTF8;
    private static byte[] _optionalEntropy = null;

    public static string Decrypt(this byte[] encryptedPassword)
    {
        if (encryptedPassword == null) throw new ArgumentNullException("encryptedPassword");
        byte[] bytes = ProtectedData.Unprotect(encryptedPassword, _optionalEntropy, DataProtectionScope.CurrentUser);
        return _encoding.GetString(bytes);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="password"></param>
    /// <returns>Empty collection if the input is null or empty.</returns>
    public static byte[] Encrypt(this string password)
    {
        if (string.IsNullOrEmpty(password)) return new byte[0];
        byte[] buffer = _encoding.GetBytes(password);
        return ProtectedData.Protect(buffer, _optionalEntropy, DataProtectionScope.CurrentUser);
    }
}

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

Initial Description
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.

Initial Title
Encrypting passwords and other sensitive information in .NET

Initial Tags
security

Initial Language
C#