Encrypt AES 256 - CSharp System.Security.Cryptography

CSharp examples for System.Security.Cryptography:AES

Description

Encrypt AES 256

Demo Code


using System.Text;
using System.Security.Cryptography;
using System;//from   w  w  w . j  a  v  a  2 s . c o  m
using Org.BouncyCastle.Utilities.Encoders;

public class Main{
        public static string Encrypt_AES256(string plainText, string keyStr)
        {
            RijndaelManaged aes = new RijndaelManaged();
            aes.BlockSize = 128;
            aes.KeySize = 256;

            // It is equal in java
            // Cipher _Cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            // Initialization vector.
            // It could be any value or generated using a random number generator.
            byte[] keyArr = Base64.Decode(keyStr);
            byte[] ivArr = { 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1, 7, 7, 7, 7 };

            aes.Key = keyArr;
            aes.IV = ivArr;

            ICryptoTransform encrypto = aes.CreateEncryptor();

            byte[] plainTextByte = Encoding.GetBytes(plainText);
            byte[] CipherText = encrypto.TransformFinalBlock(plainTextByte, 0, plainTextByte.Length);
            return Convert.ToBase64String(CipherText);
        }
}

Related Tutorials