Wanna encrypt stuff? Well Check this awesome utility that i made...
Test....
using AwesomeUtilities;
using NUnit.Framework;
namespace Test
{
[TestFixture]
public class CryptographyUtilityTest
{
[Test]
public void Should_do_some_awesome_encrytion_stuff()
{
string toEncrypt = "Encrypt Me Stud";
string encrypted = CryptographyUtility.Encrypt(toEncrypt);
Assert.AreEqual(toEncrypt, CryptographyUtility.Decrypt(encrypted));
}
}
}
The shit that does the stuff
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace AwesomeUtilities
{
public abstract class CryptographyUtility
{
private static readonly string PASSWORD;
static CryptographyUtility()
{
PASSWORD = "MyUberPassword"; //Usually taken from a *.config
}
public static string Encrypt(string value)
{
return Encrypt(value, PASSWORD);
}
public static string Decrypt(string encryptedValue)
{
return Decrypt(encryptedValue, PASSWORD);
}
public static string Encrypt(string value, string password)
{
ValidateTextData(value, password);
Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, 8);
byte[] rawData = Encoding.Unicode.GetBytes(value);
using (MemoryStream memoryStream = new MemoryStream())
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, GetRijndaelWith(keyGenerator).CreateEncryptor(), CryptoStreamMode.Write))
{
memoryStream.Write(keyGenerator.Salt, 0, keyGenerator.Salt.Length);
cryptoStream.Write(rawData, 0, rawData.Length);
cryptoStream.Close();
return Convert.ToBase64String(memoryStream.ToArray());
}
}
public static string Decrypt(string encryptedValue, string password)
{
ValidateTextData(encryptedValue, password);
byte[] rawData = GetRawData(encryptedValue);
using (MemoryStream memoryStream = new MemoryStream())
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, GetRijndaelWith(new Rfc2898DeriveBytes(password, GetSalt(rawData))).CreateDecryptor(), CryptoStreamMode.Write))
{
cryptoStream.Write(rawData, 8, rawData.Length - 8);
cryptoStream.Close();
return Encoding.Unicode.GetString(memoryStream.ToArray());
}
}
private static Rijndael GetRijndaelWith(DeriveBytes keyGenerator)
{
Rijndael aes = Rijndael.Create();
aes.IV = keyGenerator.GetBytes(aes.BlockSize/8);
aes.Key = keyGenerator.GetBytes(aes.KeySize/8);
return aes;
}
private static byte[] GetRawData(string value)
{
byte[] rawData = Convert.FromBase64String(value);
if (rawData.Length < 8)
throw new ArgumentException("Invalid input value");
return rawData;
}
private static byte[] GetSalt(byte[] rawData)
{
byte[] salt = new byte[8];
for (int i = 0; i < salt.Length; i++)
salt[i] = rawData[i];
return salt;
}
private static void ValidateTextData(string value, string password)
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("No value given");
if (string.IsNullOrEmpty(password))
throw new ArgumentException("No password given");
}
}
}

0 comments:
Post a Comment