2012년 11월 24일 토요일

AES C# Example

AES C# Example

DON'T USE BELOW CODE FOR REAL SOFTWARE.


https://github.com/ftsfranklin reported below.


Warning: Don't use this for real software.

  • RijndaelManaged is discouraged in favor of an AES implementation. (AES is a subset of Rijndael, though.) In particular, use Aes.Create() rather than the AesManaged class or anything else more explicit.
  • RijndaelManaged is not designed to be reused and kept around as a static field.
  • IV should be different and (securely) random for each ciphertext, and stored with it. IV is not a second key, but analogous to the salt in hashing, so it's not secret.
  • Because of the ToString override, it is at risk of exposing the key in log files if the Aes object is logged.

There are probably other issues, but I don't know enough to say. But this gist is publicly visible and appears on Google, so people will stumble onto it and copy it into their code.



This is AES example for C#
https://github.com/magicsih/AesExample.git

Web AES Encryptor/Decryptor: http://www.txtwizard.net/crypto

Class

using System;
using System.Security.Cryptography;
using System.Text;
 
namespace AesExample
{
    class Aes
    {
        private static RijndaelManaged rijndael = new RijndaelManaged();
        private static System.Text.UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
 
        private const int CHUNK_SIZE = 128;
 
        private void InitializeRijndael()
        {
            rijndael.Mode = CipherMode.CBC;
            rijndael.Padding = PaddingMode.PKCS7;
        }
 
        public Aes()
        {
            InitializeRijndael();
 
            rijndael.KeySize = CHUNK_SIZE;
            rijndael.BlockSize = CHUNK_SIZE;
 
            rijndael.GenerateKey();
            rijndael.GenerateIV();
        }
 
        public Aes(String base64key, String base64iv)
        {
            InitializeRijndael();
 
            rijndael.Key = Convert.FromBase64String(base64key);
            rijndael.IV = Convert.FromBase64String(base64iv);
        }
 
        public Aes(byte[] key, byte[] iv)
        {
            InitializeRijndael();
 
            rijndael.Key = key;
            rijndael.IV = iv;
        }
 
        public string Decrypt(byte[] cipher)
        {
            ICryptoTransform transform = rijndael.CreateDecryptor();
            byte[] decryptedValue = transform.TransformFinalBlock(cipher, 0, cipher.Length);
            return unicodeEncoding.GetString(decryptedValue);
        }
 
        public string DecryptFromBase64String(string base64cipher)
        {
            return Decrypt(Convert.FromBase64String(base64cipher));
        }
 
        public byte[] EncryptToByte(string cipherText)
        {
            ICryptoTransform encryptor = rijndael.CreateEncryptor();
            byte[] cipher = unicodeEncoding.GetBytes(cipherText);
            byte[] encryptedValue = encryptor.TransformFinalBlock(cipher, 0, cipher.Length);
            return encryptedValue;
        }
 
        public string EncryptToBase64String(string cipherText)
        {
            return Convert.ToBase64String(EncryptToByte(cipherText));
        }
 
        public string GetKey()
        {
            return Convert.ToBase64String(rijndael.Key);
        }
 
        public string GetIV()
        {
            return Convert.ToBase64String(rijndael.IV);
        }
 
        public override string ToString()
        {
            return "KEY:" + GetKey() + Environment.NewLine + "IV:" + GetIV();
        }
    }
}

Usage

using System;
 
namespace AesExample
{
    class Program
    {
        private const string ORIGINAL = "this is some data to encrypt";
        private const string SAMPLE_KEY = "gCjK+DZ/GCYbKIGiAt1qCA==";
        private const string SAMPLE_IV = "47l5QsSe1POo31adQ/u7nQ==";
 
        static void Main(string[] args)
        {
            //Aes aes = new Aes();    //생성자에 arguments가 없으면 key와 iv 자동생성
 
            Aes aes = new Aes(SAMPLE_KEY, SAMPLE_IV);
 
            Console.WriteLine("ORIGINAL:" + ORIGINAL);
            Console.WriteLine("KEY:" + aes.GetKey());
            Console.WriteLine("IV:" + aes.GetIV());
 
            /*string->byte->string*/
            Console.WriteLine("Example for: string->byte->string");
            byte[] encryptedBlock = aes.EncryptToByte(ORIGINAL);        //original text 를 암호화된 byte 배열로 변환
            string decryptedString = aes.Decrypt(encryptedBlock);       //암호화된 byte 배열을 original text로 복호화
            Console.WriteLine(decryptedString);
 
            /*string->base64->string*/
            Console.WriteLine("Example for: string->base64->string");
            string encryptedBase64String = aes.EncryptToBase64String(ORIGINAL);     //original text를 암호화된 base64 string으로 변환
            decryptedString = aes.DecryptFromBase64String(encryptedBase64String);   //암호호된 base64 string을 original text로 복호화
 
            Console.WriteLine(encryptedBase64String);
            Console.WriteLine(decryptedString);
 
            Console.ReadLine();
        }
    }
}