IRONSOFTWAREHOME
개발자 업데이트

C# AES 암호화 (개발자를 위한 작동 방식)

제이콥 멜러, 팀 아이언 최고기술책임자
Jacob Mellor
Updated: 2026년 4월 21일

AES (고급 암호화 표준)은 가장 일반적으로 사용되는 대칭 암호화 알고리즘 중 하나입니다. AES 암호화는 동일한 키를 사용하여 데이터를 암호화하고 해독하므로 많은 애플리케이션에서 민감한 데이터를 보호하는 데 효율적이고 빠릅니다.

이 튜토리얼은 C#에서 AES 암호화에 중점을 두고, AES 클래스를 사용하여 데이터를 암호화하고 복호화하며 IronPDF 라이브러리를 사용하는 방법을 다룹니다. 실제 예제를 다루고, 암호화 과정을 걸어보며, 보안을 강화하기 위해 암호화 블록 체인(CBC) 모드를 사용하는 방법을 알아봅니다. 또한 암호화 키 관리와 초기화 벡터(IV)의 역할에 대해서도 논의할 것입니다.

Introduction of AES Encryption in C#

고급 암호화 표준(AES)은 미국 국립 표준 기술 연구소(NIST)에 의해 표준화된 대칭 암호화 알고리즘입니다. 이 알고리즘은 128, 192 또는 256 비트의 키 크기를 가질 수 있으며 기밀 데이터 암호화에 매우 안전합니다. 동일한 암호화 키를 사용하여 데이터를 암호화하고 복호화합니다.

AES는 원본 데이터를 블록으로 나누고 그 블록에 변환을 적용하여 작동합니다. CBC(암호화 블록 체인) 및 전자 코드 북(ECB)과 같이 다양한 암호 모드로 작동하며, 각각 다양한 보안 기능을 제공합니다.

How AES Works in C#

C#의 AES 암호화 알고리즘은 System.Security.Cryptography 네임스페이스의 일부입니다. 이 네임스페이스에는 AES 클래스가 포함되어 있으며, AES 인스턴스를 생성하고, 키 크기, 암호 모드, 패딩 모드를 지정한 다음, 비밀 키를 사용하여 데이터를 암호화하고 복호화할 수 있습니다.

C#에서 AES를 사용하려면 다음 기본 단계를 따르십시오:

  1. AES 클래스의 인스턴스를 Aes.Create()을 사용하여 생성합니다.
  2. 키, IV 및 암호 모드와 같은 관련 매개변수를 설정합니다.
  3. ICryptoTransform 인터페이스를 사용하여 데이터를 암호화하고 MemoryStream에 기록합니다.
  4. 동일한 키와 IV를 사용하여 데이터를 복호화합니다.

C#에서 기본적인 암호화 과정 및 복호화 프로그램을 만들어봅시다.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

class Program
{
    // Declare a static byte array for encrypted data
    public static byte[] encryptedData;

    // Main method to demonstrate encryption and decryption
    public static void Main(string[] args)
    {
        // String plaintext to be encrypted
        string plaintext = "This is some sensitive data!";
        string key = "abcdefghijklmnop"; // 128-bit key (16 characters)

        // Encrypt the plaintext
        string ciphertext = Encrypt(plaintext, key);
        Console.WriteLine("Encrypted Data: " + ciphertext);

        // Decrypt the ciphertext
        string decryptedData = Decrypt(ciphertext, key);
        Console.WriteLine("Decrypted Data: " + decryptedData);
    }

    // Method to encrypt data
    public static string Encrypt(string plaintext, string key)
    {
        // Create a new instance of the AES encryption algorithm
        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = new byte[16]; // Initialization vector (IV)

            // Create an encryptor to perform the stream transform
            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

            // Create the streams used for encryption
            using (MemoryStream ms = new MemoryStream())
            {
                // Create a CryptoStream using the encryptor
                using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter sw = new StreamWriter(cs))
                    {
                        sw.Write(plaintext);
                    }
                }
                // Store the encrypted data in the public static byte array
                encryptedData = ms.ToArray();
                return Convert.ToBase64String(encryptedData);
            }
        }
    }

    // Method to decrypt data
    public static string Decrypt(string ciphertext, string key)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = new byte[16]; // Initialization vector (IV)

            // Create a decryptor to perform the stream transform
            ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

            // Create the streams used for decryption
            using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(ciphertext)))
            {
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader sr = new StreamReader(cs))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }
        }
    }
}

C# AES 암호화 (개발자를 위한 작동 방식): 그림 1 - 메모리 스트림을 사용한 암호화 및 복호화 출력

코드 설명

  1. Aes.Create(): 이는 AES 암호화 알고리즘의 새 인스턴스를 생성합니다.
  2. aes.Key: 암호화와 복호화에 모두 사용되는 키입니다. 유효한 크기, 예를 들어 128 비트(16 바이트), 192 비트 또는 256 비트여야 합니다.
  3. aes.IV: 초기화 벡터(IV)는 암호화 과정을 임의화하는 데 사용됩니다. 이 예에서는 간단히 위해 0으로 된 IV를 사용합니다.
  4. MemoryStream: 암호화된 데이터를 바이트 스트림으로 작업할 수 있도록 합니다.
  5. CryptoStream: 데이터 스트림(암호화 또는 복호화)를 변형합니다.

고급 예제: 사용자 정의 키와 IV를 사용한 AES 암호화

이전 예제를 기반으로 무작위 IV를 생성하여 암호화를 더욱 안전하게 하겠습니다.

public static string EncryptData(string plaintext)
{
    using (Aes aes = Aes.Create())
    {
        aes.Key = new byte[32]; // AES-256 requires a 256-bit key (32 bytes)
        aes.IV = new byte[16];  // 128-bit block size

        // Randomly generate key and IV
        using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
        {
            rng.GetBytes(aes.Key); // Generate a random key
            rng.GetBytes(aes.IV);  // Generate a random IV
        }

        // Create an encryptor to perform the stream transform
        ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

        // Create the streams used for encryption
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
            {
                using (StreamWriter sw = new StreamWriter(cs))
                {
                    sw.Write(plaintext);
                }
            }
            return Convert.ToBase64String(ms.ToArray());
        }
    }
}

이 경우 함수가 호출될 때마다 새로운 키IV를 생성합니다. 이렇게 하면 더 강력한 암호화가 제공되며 동일한 키가 모든 작업에 사용되지 않습니다. AES는 키 크기를 128, 192 및 256 비트로 지원합니다.

AES를 사용한 데이터 복호화

복호화는 데이터를 암호화하는 과정의 반대입니다. 예제에서는 암호화에 사용된 동일한 키와 IV가 데이터를 복호화하기 위해 제공되어야 합니다. 복호화 과정은 암호화된 데이터를 원래 형태로 변환하는 것을 포함합니다.

기존에 암호화된 데이터를 사용하는 예제입니다:

public static string DecryptData(string ciphertext, byte[] key, byte[] iv)
{
    using (Aes aes = Aes.Create())
    {
        aes.Key = key;
        aes.IV = iv;

        // Create a decryptor to perform the stream transform
        ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

        // Create the streams used for decryption
        using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(ciphertext)))
        {
            using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
            {
                using (StreamReader sr = new StreamReader(cs))
                {
                    return sr.ReadToEnd();
                }
            }
        }
    }
}

이 코드는 암호화된 데이터를 다시 원본 데이터로 복호화합니다.

IronPDF와 AES 암호화

IronPDF는 간단한 C# 코드를 사용하여 PDF를 생성, 편집, 조작하도록 설계된 간단하고 개발자 친화적인 .NET 라이브러리입니다. 개발자가 HTML, CSS 및 JavaScript에서 직접 PDF 문서를 생성할 수 있게 하여 동적으로 보고서, 송장 또는 기타 문서를 생성하는 데 매우 유용합니다. 병합, 분할, 비밀번호나 디지털 서명 같은 보안 기능 추가도 지원하여 IronPDF는 .NET 응용 프로그램에서 PDF 생성의 포괄적인 솔루션입니다.

IronPDF와 AES 암호화 통합

C# AES 암호화 (개발자를 위한 작동 방식): 그림 2 - IronPDF

민감한 보고서나 문서를 생성할 때, 공유하기 전에 해당 PDF 내 데이터를 암호화해야 할 수 있습니다. AES(고급 암호화 표준) 암호화는 PDF 파일의 내용을 안전하게 암호화하는 완벽한 솔루션입니다. IronPDF와 AES 암호화를 결합하여 PDF 내 데이터를 보호하면서도 문서 자체를 작업할 수 있는 능력을 유지할 수 있습니다.

단계 1: IronPDF를 사용하여 PDF 생성

ChromePdfRenderer 클래스를 사용하여 HTML 콘텐츠로부터 PDF를 생성하고 파일에 저장하십시오:

var htmlContent = "<h1>Confidential</h1><p>This is sensitive data.</p>";
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs(@"C:\Reports\ConfidentialReport.pdf");

단계 2: AES를 사용하여 PDF 암호화

PDF가 생성되면 **AES:**로 암호화하십시오.

byte[] pdfBytes = File.ReadAllBytes(@"C:\Reports\ConfidentialReport.pdf");
using (Aes aes = Aes.Create())
{
    aes.Key = Encoding.UTF8.GetBytes("abcdefghijklmnop");
    aes.IV = new byte[16];
    using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
    using (var ms = new MemoryStream())
    {
        using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
        {
            cs.Write(pdfBytes, 0, pdfBytes.Length);
        }
        File.WriteAllBytes(@"C:\Reports\ConfidentialReport.encrypted", ms.ToArray());
    }
}

결론

IronPDF와 AES 암호화를 통합하면 접근 가능하면서도 암호화된 안전한 문서를 동적으로 생성할 수 있습니다. 안전한 문서 생성이 필요한 애플리케이션을 개발하거나 민감한 보고서를 관리할 때, IronPDF와 강력한 암호화를 결합하여 데이터를 보호합니다. IronPDF는 PDF 작업을 단순화하고, AES는 콘텐츠의 안전성을 보장합니다.

IronPDF는 무료 체험판을 제공하여 개발자가 기능을 먼저 탐색해볼 수 있습니다. 프로젝트에 IronPDF를 구현할 준비가 되었다면, 라이선스는 $999부터 시작하는 일회성 구매로 가능합니다.

제이콥 멜러, 팀 아이언 최고기술책임자
최고기술책임자

제이콥 멜러는 Iron Software의 최고 기술 책임자(CTO)이자 C# PDF 기술을 개척한 선구적인 엔지니어입니다. Iron Software의 핵심 코드베이스를 최초로 개발한 그는 창립 초기부터 회사의 제품 아키텍처를 설계해 왔으며, CEO인 캐머런 리밍턴과 함께 회사를 NASA, 테슬라, 그리고 전 세계 정부 기관에 서비스를 제공하는 50명 이상의 직원을 보유한 기업으로 성장시켰습니다.

...
더 읽어보기

관련 기사

Key in blue circle

무료 30일 체험 키를 즉시 받으세요.

Your trial license will be sent to your email address

제한 없음. 100% 무제한 이용. 신용카드 불필요.

bullet_checked신용카드나 계정 생성은 필요하지 않습니다.제한 없음. 100% 무제한 이용. 신용카드 불필요.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
무료 라이브 데모를 예약하세요
Booking Badge

전 세계 수백만 엔지니어들이 신뢰하는 제품입니다.

Iron Software의 고객 로고
부담 없는 무료 상담을 받아보세요
아래 양식을 작성하시거나 sales@ironsoftware.com으로 이메일을 보내주세요.
고객님의 정보는 항상 비밀로 유지됩니다.
전 세계 수백만 엔지니어들이 신뢰하는 제품입니다.
Iron Software의 고객 로고
지금 바로 30일 무료 체험판 키를 받으세요.
신용카드나 계정 생성은 필요하지 않습니다.