New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Encrypt Method

159 Views
Copy Code Show/Hide Line Numbers
   1:          /// <summary>
   2:          /// Encrypts a string at the current user's scope using DPAPI.
   3:          /// </summary>
   4:          /// <param name="toEncrypt">The string to encrypt.</param>
   5:          /// <param name="key">The key used to encrypt it.</param>
   6:          /// <returns>
   7:          /// The encrypted bytes that only the current user, with the specified key,
   8:          /// can decrypt again.
   9:          /// </returns>
  10:          /// <seealso cref="CR_CodeTweet.ByteExtensions.Decrypt" />
  11:          public static byte[] Encrypt(this string toEncrypt, string key)
  12:          {
  13:              if (toEncrypt == null)
  14:              {
  15:                  throw new ArgumentNullException("toEncrypt");
  16:              }
  17:              if (key == null)
  18:              {
  19:                  throw new ArgumentNullException("key");
  20:              }
  21:              if (key.Length == 0)
  22:              {
  23:                  throw new ArgumentException("Key may not be empty.", "key");
  24:              }
  25:              byte[] entropy = Encoding.Unicode.GetBytes(key);
  26:              byte[] toEncryptBytes = Encoding.Unicode.GetBytes(toEncrypt);
  27:              byte[] encrypted = ProtectedData.Protect(toEncryptBytes, entropy, DataProtectionScope.CurrentUser);
  28:              return encrypted;
  29:          }
by Mehul Harry
  December 15, 2009 @ 4:07pm
Tags:
Comment:
Saves and retrieves a string using API

Add a comment


Report Abuse
brought to you by:
West Wind Techologies


If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate