17 May 2011

C# - Encryption/decryption

I wrote these extensions to easily encrypt strings and later decrypt them again.

Keys

First the encryption will need these.
For each project I use them in, I change the keys a little.
private static readonly byte[] KEY = { 15, 85, 64, 52, 131, 86, 216, 44 };
private static readonly byte[] IV = { 5, 44, 19, 95, 129, 164, 9, 108 };

Encrypt

public static string Encrypt(this string source) {
  try {
    if (string.IsNullOrEmpty(source))
      return source;
    else {
      using (var des = new DESCryptoServiceProvider())
      using (var ms = new MemoryStream())
      using (var cs = new CryptoStream(ms, des.CreateEncryptor(KEY, IV), CryptoStreamMode.Write))
      using (var sw = new StreamWriter(cs))
      {
          sw.Write(source);
          sw.Flush();
          cs.FlushFinalBlock();
          sw.Flush();
          return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
      }
    }
  }
  catch {
    return string.Empty;
  }
}

Decrypt

public static string Decrypt(this string source) {
  try {
    if (string.IsNullOrEmpty(source))
      return source;
    else {
      using (var des = new DESCryptoServiceProvider())
      using (var ms = new MemoryStream(Convert.FromBase64String(source)))
      using (var cs = new CryptoStream(ms, des.CreateDecryptor(KEY, IV), CryptoStreamMode.Read))
      using (var sr = new StreamReader(cs))
      {
          return sr.ReadToEnd();
      }
    }
  }
  catch {
    return string.Empty;
  }
}

No comments:

Post a Comment