Created
January 19, 2012 11:25
-
-
Save tjrobinson/1639492 to your computer and use it in GitHub Desktop.
MachineKeyBasedEncryptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.IO.Compression; | |
using System.Text; | |
using System.Web; | |
using System.Web.Security; | |
public static class MachineKeyBasedEncryptor | |
{ | |
public static string Encrypt(string value) | |
{ | |
if (string.IsNullOrEmpty(value)) | |
{ | |
throw new ArgumentNullException("value"); | |
} | |
string encryptedValue = MachineKey.Encode(Encoding.ASCII.GetBytes(value), MachineKeyProtection.Encryption); | |
return encryptedValue; | |
} | |
public static string Decrypt(string value) | |
{ | |
if (string.IsNullOrEmpty(value)) | |
{ | |
throw new ArgumentNullException("value"); | |
} | |
return Encoding.Unicode.GetString(MachineKey.Decode(value, MachineKeyProtection.Encryption)); | |
} | |
public static string EncryptAndUrlEncode(string value) | |
{ | |
if (string.IsNullOrEmpty(value)) | |
{ | |
throw new ArgumentNullException("value"); | |
} | |
string encryptedValue = Encrypt(value); | |
byte[] encryptedValueBuffer = Encoding.ASCII.GetBytes(encryptedValue); | |
return HttpServerUtility.UrlTokenEncode(encryptedValueBuffer); | |
} | |
public static string UrlDecodeAndDecrypt(string value) | |
{ | |
if (string.IsNullOrEmpty(value)) | |
{ | |
throw new ArgumentNullException("value"); | |
} | |
byte[] unencodedValueBuffer = HttpServerUtility.UrlTokenDecode(value); | |
string unencodedValue = Encoding.UTF8.GetString(unencodedValueBuffer); | |
string decryptedValue = Decrypt(unencodedValue); | |
return decryptedValue; | |
} | |
public static string Compress(string value) | |
{ | |
using (var ms = new MemoryStream()) | |
{ | |
using (var zip = new GZipStream(ms, CompressionMode.Compress, true)) | |
{ | |
zip.Write(Encoding.UTF8.GetBytes(value), 0, value.Length); | |
} | |
return Convert.ToBase64String(ms.ToArray()); | |
} | |
} | |
public static string Decompress(string value) | |
{ | |
using (var ms = new MemoryStream(Convert.FromBase64String(value))) | |
{ | |
using (var zip = new GZipStream(ms, CompressionMode.Decompress, true)) | |
{ | |
using (var reader = new BinaryReader(zip)) | |
{ | |
return Encoding.UTF8.GetString(reader.ReadBytes(10000)); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment