Encrypt text with AES Key - CSharp System.Security.Cryptography

CSharp examples for System.Security.Cryptography:AES

Description

Encrypt text with AES Key

Demo Code


using System.Text;
using System.Security.Cryptography;
using System.Linq;
using System.Collections.Generic;
using System;/*from  w  w w  .  ja va  2s  .  co  m*/

public class Main{

        private static string Encrypt(string key, string iv, string txt)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);
            byte[] txtArray = UTF8Encoding.UTF8.GetBytes(txt);

            RijndaelManaged rDel = new RijndaelManaged();
            rDel.BlockSize = 128;
            rDel.KeySize = 128;
            rDel.Key = keyArray;
            rDel.IV = ivArray;
            rDel.Mode = CipherMode.CBC;
            rDel.Padding = PaddingMode.PKCS7;

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

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

        public static string Encrypt(string txt)
        {
            return Encrypt(ConfigHelper.GetConfigString("AESKey"), ConfigHelper.GetConfigString("AESIV"), txt);
        }
}

Related Tutorials