/ .net

Useful AES cipher class

Transforms any text to/from URL friendly encrypted text.

/// <summary>
/// Encrypts and decrypts string using the AES algorithm.
/// <example><c><![CDATA[
///   Cipher _cipher = new Cipher("veryhardtoguess");
///   var text = "protectme";
///   Console.WriteLine("Original: " + text);
///   var encrypted = _cipher.Encrypt(text);
///   Console.WriteLine("Encrypted: " + encrypted);
///   var decrypted = _cipher.Decrypt(encrypted);
///   Console.WriteLine("Decrypted: " + decrypted);
/// ]]></c></example>
/// </summary>
class Cipher
{
    readonly ICryptoTransform _encryptor;
    readonly ICryptoTransform _decryptor;

    public Cipher(string password)
    {
        var sp = CreateSP(password);
        _encryptor = sp.CreateEncryptor();
        _decryptor = sp.CreateDecryptor();
    }

    private static AesCryptoServiceProvider CreateSP(string password)
    {
        var sp = new AesCryptoServiceProvider()
        {
            Key = CreateKey(password),
            Mode = CipherMode.ECB,
            Padding = PaddingMode.ISO10126,
        };
        return sp;
    }

    private static byte[] CreateKey(string password)
    { 
        var key = Encoding.Unicode.GetBytes(password);
        Array.Resize(ref key, 256 / 8);
        return key;
    }

    public string Encrypt(string text)
    {
        var buf = Encoding.Unicode.GetBytes(text);
        var encrypted = _encryptor.TransformFinalBlock(buf, 0, buf.Length);
        return Encode(encrypted);
    }

    public string Decrypt(string encryptedText)
    {
        var encryptedBuf = Decode(encryptedText);
        var buf = _decryptor.TransformFinalBlock(encryptedBuf, 0, encryptedBuf.Length);
        return Encoding.Unicode.GetString(buf);
    }        

    static string Encode(byte[] payload)
    {
        string base64 = Convert.ToBase64String(payload);
        string base64Url = new string(
            base64.ToCharArray().TakeWhile((ch) => ch != '=').Select((ch) => ch == '+' ? '-' : ch == '/' ? '_' : ch).ToArray()
            );
        return base64Url;
    }

    static byte[] Decode(string base64Url)
    {
        string base64 = new string(base64Url.ToCharArray().Select((ch) => ch == '-' ? '+' : ch == '_' ? '/' : ch).ToArray())
            + ((base64Url.Length % 4) != 0 ? new string('=', 4 - (base64Url.Length % 4)) : string.Empty);
        return Convert.FromBase64String(base64);
    }
}