• Simple AES (Rijndael) C# Encrypt & Decrypt functions

    [c#]
    post by bgaidu / 2009-1-15 15:09 Thursday
    I simply re-purposed Bobby Derosa’s Triple DES (3DES) Encrypt() and Decrypt() functions to provide a simple and straight-forward way to use AES symmetrical encryption safe for use on such things as UTF-8 and/or HTTP GET string compatibility. I’m using this in ASP.NET AJAX-enabled applications.
    <br/>I’m only using a 256bit (32byte) key for these example functions.

    Encrypt()

    public static string Encrypt(string toEncrypt) {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12345678901234567890123456789012");
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

        RijndaelManaged rDel = new RijndaelManaged();
        rDel.Key = keyArray;
        rDel.Mode = CipherMode.ECB;
        rDel.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = rDel.CreateEncryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }

    Download this code: rijndael.encrypt.cs

    Encrypt()

    public static string Decrypt(string toDecrypt) {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12345678901234567890123456789012");
        byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);

        RijndaelManaged rDel = new RijndaelManaged();
        rDel.Key = keyArray;
        rDel.Mode = CipherMode.ECB;
        rDel.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = rDel.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

        return UTF8Encoding.UTF8.GetString(resultArray);
    }

    Download this code:
    
    您对本文的评分:
    当前平均分: 0.0(0 次打分)

    引用地址:

    发表评论: