Aes Encrypt String with key - CSharp System.Security.Cryptography

CSharp examples for System.Security.Cryptography:AES

Description

Aes Encrypt String with key

Demo Code


using System.Text;
using System.Security.Cryptography;
using System;/* w w  w.  j av a2  s .  c  o m*/
using Org.BouncyCastle.Utilities.Encoders;

public class Main{
        public static string AesEncrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
            byte[] keyByte = Convert.FromBase64String(key);

            RijndaelManaged aes = new System.Security.Cryptography.RijndaelManaged
            {
                Key = keyByte,
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

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

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

Related Tutorials