IRONSOFTWAREHOME
開発者向けアップデート

C# AES暗号化(開発者向けの仕組み)

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: 2026年4月21日

AES(高度暗号化標準)は、最も一般的に使用される対称暗号化アルゴリズムの1つです。 データを暗号化および復号化するために同じキーを使用するため、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.Create()を使用してAESクラスのインスタンスを作成します。
  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)は、暗号化プロセスをランダム化するために使用されます。 この例では、シンプルさのためにゼロの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();
                }
            }
        }
    }
}

このコードは暗号化されたデータ元のデータに戻します。

AES暗号化を使用したIronPDF

IronPDFは、シンプルで開発者フレンドリーな.NETライブラリで、簡単なC#コードを使用してPDFを生成、編集、および操作するために設計されています。 開発者がHTML、CSS、およびJavaScriptから直接PDFドキュメントを作成することを可能にし、動的なレポート、請求書、その他のドキュメントの生成に非常に便利です。 マージ、分割、さらにはパスワードやデジタル署名などのセキュリティ機能を追加するサポートを備えたIronPDFは、.NETアプリケーションでのPDF生成の包括的なソリューションです。

AES暗号化との統合によるIronPDFの活用

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());
    }
}

結論

C# AES 暗号化 (開発者向けの仕組み): 図 3 - ライセンス

IronPDFとAES暗号化を統合することで、アクセス可能でありながら暗号化された動的で安全なドキュメントを生成することができます。 安全なドキュメント生成を必要とするアプリケーションの開発や機密レポートの管理において、強固な暗号化との統合によってデータを保護します。 IronPDFはPDFの取り扱いを簡略化し、AESはコンテンツが安全であることを保証します。

IronPDFは無料トライアルを提供しており、開発者はその機能を検討する前に探索することが容易です。 IronPDF をプロジェクトに実装する準備ができたら、ライセンスは一度限りの購入で$999から始まります。

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.

...
Read More

Related Articles

Key in blue circle

無料の30日間トライアルキーをすぐに入手してください。

bullet_checkedクレジットカードやアカウントの作成は不要です。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
無料のライブデモを予約する
Booking Badge related to IronPDF Product Demo

世界中の数百万人のエンジニアから信頼されています。

ライセンスはより安く
義務のない相談を受ける
下記のフォームを記入するか、sales@ironsoftware.comにメールしてください。
あなたの詳細は常に守秘されます。
世界中の数百万人のエンジニアから信頼されています。
ライセンスはより安く
あなたの無料30日間の試用キーをすぐに入手。
クレジットカードやアカウントの作成は不要です。