AES Encrypt string by string key - CSharp System.Security.Cryptography

CSharp examples for System.Security.Cryptography:AES

Description

AES Encrypt string by string key

Demo Code


using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.Linq;
using System.IO;// w  w  w  . ja v  a  2 s .co m
using System.Collections.Generic;
using System;

public class Main{
        public static string AESEncrypt(string data, string key)
        {
            MemoryStream mStream = new MemoryStream();
            RijndaelManaged aes = new RijndaelManaged();
            byte[] plainBytes = Encoding.UTF8.GetBytes(data);
            Byte[] bKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length);
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;
            aes.KeySize = 128;
            aes.Key = bKey;
            CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
            try
            {
                cryptoStream.Write(plainBytes, 0, plainBytes.Length);
                cryptoStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            finally
            {
                cryptoStream.Close();
                mStream.Close();
                aes.Clear();
            }
        }
}

Related Tutorials