메뉴 건너뛰기

Dev tips

ASP.NET [c#] AES-128/ECB/PKCS7-padding Encrypt/Decrypt

taknim 2015.05.29 03:29 조회 수 : 2464 추천:332

    public class AESCipher
    {
        public static string Encrypt(string plainText, string key)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); // 128-AES key
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(plainText);
            RijndaelManaged rijndaelManaged = new RijndaelManaged();
            rijndaelManaged.Key = keyArray;
            rijndaelManaged.Mode = CipherMode.ECB;
            rijndaelManaged.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rijndaelManaged.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray);
        }

        public static string Decrypt(string encryptedText, string key)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); // AES-128 key
            byte[] toEncryptArray = Convert.FromBase64String(encryptedText);
            RijndaelManaged rijndaelManaged = new RijndaelManaged();
            rijndaelManaged.Key = keyArray;
            rijndaelManaged.Mode = CipherMode.ECB;
            rijndaelManaged.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rijndaelManaged.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Encoding.UTF8.GetString(resultArray);
        }
    }

padding 는 None 로 했을때 오류가 발생한다. 이유를 알수가 없다. ㅠㅠ
결국 PKCS7 로 사용한 코딩으로 사용했다.

함수 파라미터에서 key 는 16자 ascii 문자열이면 된다. (예:1234567890123456)

AES-128 - BlockSize:128, KeySize:128
AES-192 - BlockSize:128, KeySize:192
AES-256 - BlockSize:128, KeySize:256