.NET ヘルプ

BouncyCastle C#(開発者向けの仕組み)

チペゴ
チペゴ・カリンダ
2024年1月14日
共有:

BouncyCastle C# は、.NET 開発者向けに幅広い暗号化アルゴリズムとツールを提供する総合的なライブラリです。 このガイドは、Bouncy Castleの基本を初心者に紹介し、そのセキュリティプロバイダとしての機能を強調し、日常使用のための実用的な例を提供することを目的としています。 また、IronPDF .NET PDF Libraryとどのように使用できるかについても学びます。

Bouncy Castle の紹介

Bouncy Castle は、暗号化セキュリティの分野で強力かつ多用途なライブラリとして際立っています。 それは、JavaおよびC#向けに高品質なセキュリティサービスを提供することを目的とした登録されたオーストラリアのチャリティープロジェクトです。 ライブラリは、MIT X Consortium License に基づくライセンスで管理されており、広範な利用と貢献を推奨しています。

Bouncy Castle の目的を理解する

Bouncy Castleは、広範な暗号アルゴリズムを提供するセキュリティプロバイダーとして機能します。 その多様性により、基本的な暗号化から複雑なデジタル署名まで、さまざまなセキュリティニーズに対応できます。 初心者として、Bouncy Castle の範囲を理解することは、プロジェクトに効果的に実装するための鍵です。

C#でのBouncy Castleの始め方

C#でBouncy Castleを実装するには、まず環境を設定し、その基本コンポーネントを理解することから始めます。

設定

ライブラリをダウンロード: 開始するには、公式の Bouncy Castle ウェブサイト から最新バージョンの Bouncy Castle パッケージをダウンロードしてください。 あなたのプロジェクトのニーズに合った正しいバージョンを選択してください。

プロジェクトに統合する: ダウンロード後、Bouncy CastleをC#プロジェクトに統合します。 これは通常、プロジェクト設定にライブラリを参照として追加することを含みます。

NuGetパッケージマネージャーの検索バーで「Bouncycastle」を検索して、NuGetパッケージマネージャーを使用してもダウンロードおよびインストールすることができます。

BouncyCastle C#(開発者にとっての動作方法): 図1 - NuGetパッケージマネージャの検索バーに「Bouncycastle」と入力して、NuGetパッケージマネージャを使ってBouncy Castleをダウンロードしてインストールする

基本的な暗号化の例

この例では、C#でBouncy Castleを使用したAES(Advanced Encryption Standard)による簡単な暗号化シナリオを示します。

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System.Text;
public class SimpleEncryption
{
    public static byte[] EncryptData(string message, string password)
    {
        // Generate a random salt
        var salt = new byte[8];
        new SecureRandom().NextBytes(salt);
        // Derive key and IV from the password and salt
        Pkcs5S2ParametersGenerator generator = new Pkcs5S2ParametersGenerator();
        generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, 1000);
        ParametersWithIV keyParam = (ParametersWithIV)generator.GenerateDerivedMacParameters(256 + 128);
        // Create AES cipher in CBC mode with PKCS7 padding
        var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()));
        cipher.Init(true, keyParam);
        // Convert message to byte array and encrypt
        byte[] inputBytes = Encoding.UTF8.GetBytes(message);
        byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)];
        int length = cipher.ProcessBytes(inputBytes, 0, inputBytes.Length, outputBytes, 0);
        cipher.DoFinal(outputBytes, length);
        return outputBytes;
    }
}
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System.Text;
public class SimpleEncryption
{
    public static byte[] EncryptData(string message, string password)
    {
        // Generate a random salt
        var salt = new byte[8];
        new SecureRandom().NextBytes(salt);
        // Derive key and IV from the password and salt
        Pkcs5S2ParametersGenerator generator = new Pkcs5S2ParametersGenerator();
        generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, 1000);
        ParametersWithIV keyParam = (ParametersWithIV)generator.GenerateDerivedMacParameters(256 + 128);
        // Create AES cipher in CBC mode with PKCS7 padding
        var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()));
        cipher.Init(true, keyParam);
        // Convert message to byte array and encrypt
        byte[] inputBytes = Encoding.UTF8.GetBytes(message);
        byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)];
        int length = cipher.ProcessBytes(inputBytes, 0, inputBytes.Length, outputBytes, 0);
        cipher.DoFinal(outputBytes, length);
        return outputBytes;
    }
}
Imports Org.BouncyCastle.Crypto
Imports Org.BouncyCastle.Crypto.Engines
Imports Org.BouncyCastle.Crypto.Generators
Imports Org.BouncyCastle.Crypto.Modes
Imports Org.BouncyCastle.Crypto.Parameters
Imports Org.BouncyCastle.Security
Imports System.Text
Public Class SimpleEncryption
	Public Shared Function EncryptData(ByVal message As String, ByVal password As String) As Byte()
		' Generate a random salt
		Dim salt = New Byte(7){}
		Call (New SecureRandom()).NextBytes(salt)
		' Derive key and IV from the password and salt
		Dim generator As New Pkcs5S2ParametersGenerator()
		generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, 1000)
		Dim keyParam As ParametersWithIV = CType(generator.GenerateDerivedMacParameters(256 + 128), ParametersWithIV)
		' Create AES cipher in CBC mode with PKCS7 padding
		Dim cipher = New PaddedBufferedBlockCipher(New CbcBlockCipher(New AesEngine()))
		cipher.Init(True, keyParam)
		' Convert message to byte array and encrypt
		Dim inputBytes() As Byte = Encoding.UTF8.GetBytes(message)
		Dim outputBytes(cipher.GetOutputSize(inputBytes.Length) - 1) As Byte
		Dim length As Integer = cipher.ProcessBytes(inputBytes, 0, inputBytes.Length, outputBytes, 0)
		cipher.DoFinal(outputBytes, length)
		Return outputBytes
	End Function
End Class
$vbLabelText   $csharpLabel

このコードスニペットは、基本的な暗号化方法の作成方法を示しています。 実装のセキュリティを確保するために、発生する可能性のある例外を適切に処理することが重要です。 このメソッドを使用するには、EncryptDataを呼び出し、暗号化したいメッセージとパスワードを指定します。 例えば:

string message = "Hello, this is a test message!";
string password = "StrongPassword123";
byte[] encryptedMessage = SimpleEncryption.EncryptData(message, password);
Console.WriteLine("Original Message: " + message);
Console.WriteLine("Encrypted Message: " + BitConverter.ToString(encryptedMessage));
string message = "Hello, this is a test message!";
string password = "StrongPassword123";
byte[] encryptedMessage = SimpleEncryption.EncryptData(message, password);
Console.WriteLine("Original Message: " + message);
Console.WriteLine("Encrypted Message: " + BitConverter.ToString(encryptedMessage));
Dim message As String = "Hello, this is a test message!"
Dim password As String = "StrongPassword123"
Dim encryptedMessage() As Byte = SimpleEncryption.EncryptData(message, password)
Console.WriteLine("Original Message: " & message)
Console.WriteLine("Encrypted Message: " & BitConverter.ToString(encryptedMessage))
$vbLabelText   $csharpLabel

この例は非常に基本的なもので、入門として役立ちます。 実際のアプリケーションでは、暗号化データと共にソルトとIVを保存し、暗号化プロセス中に発生する可能性のある例外を処理するなど、より堅牢な手法を検討すべきです。

BouncyCastle C#(開発者向けの動作方法): 図2 - コンソール出力

高度な使用法とカスタマイズ

Bouncy Castleは基本的な機能に限定されません。 それはカスタマイズを可能にし、先進的な暗号アルゴリズムをサポートします。

NTRUプライムおよびその他の高度なアルゴリズム

Bouncy Castleは、NTRU Primeを含むさまざまなアルゴリズムのサポートを提供します。 これにより、開発者は自分の特定のニーズに最も適したアルゴリズムを選択する柔軟性が得られます。

例外処理とセキュリティのベストプラクティス

暗号化アプリケーションでは適切な例外処理が重要です。 Bouncy Castleのメソッドは例外を投げることがあり、これを適切に処理することで強固で安全なアプリケーションを保証します。

Bouncy CastleとIronPDFの統合

BouncyCastle C#(開発者向けの仕組み):図3 - IronPDF for .NET:C# PDFライブラリ

IronPDF は、Bouncy Castleと連携してPDFドキュメントを操作する機能を提供し、その後、Bouncy Castleの暗号化機能を使用してセキュリティを確保できます。 以下のようにして、これら2つの強力なライブラリを統合できます。

IronPDFの際立った機能は、すべてのレイアウトとスタイルを保持するHTMLからPDFへの変換機能です。 ウェブコンテンツをPDFに変換し、レポート、請求書、およびドキュメントに適しています。 HTMLファイル、URL、およびHTML文字列をシームレスにPDFに変換できます。

IronPDFを始めましょう

今日から無料トライアルでIronPDFをあなたのプロジェクトで使い始めましょう。

最初のステップ:
green arrow pointer


using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

NuGet パッケージマネージャーを使用してインストール

NuGetパッケージマネージャを使用してIronPDFをBouncy Castle C#プロジェクトに統合するには、以下の手順に従ってください:

  1. Visual Studioを開き、ソリューションエクスプローラーでプロジェクトを右クリックします。

  2. コンテキストメニューから「NuGetパッケージの管理...」を選択してください。

  3. 「参照」タブに移動して、「IronPDF」を検索してください。

  4. 検索結果からIronPDFライブラリを選択し、インストールボタンをクリックします。

  5. ライセンス契約のプロンプトをすべて受け入れます。

    IronPDFをパッケージマネージャーコンソールからプロジェクトに組み込みたい場合は、パッケージマネージャーコンソールで以下のコマンドを実行してください:

Install-Package IronPdf

それは、プロジェクトにIronPDFを取得してインストールします。

NuGetウェブサイトを使用してインストール

IronPDFの機能、互換性、その他のダウンロードオプションに関する詳細な概要については、NuGetウェブサイトのIronPDFページ https://www.nuget.org/packages/IronPdf をご覧ください。

DLLを使ってインストール

あるいは、DLLファイルを使用してIronPDFをプロジェクトに直接組み込むこともできます。このIronPDF Direct DownloadからDLLを含むZIPファイルをダウンロードしてください。 解凍して、プロジェクトにDLLを含めてください。

IronPDFを使用したPDFの生成

まず、IronPDFを使用してシンプルなPDFドキュメントを作成しましょう。

using IronPdf;
public class PdfGenerator
{
    public static void CreateSimplePdf(string filePath, string content)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(content);
        pdf.SaveAs(filePath);
    }
}
using IronPdf;
public class PdfGenerator
{
    public static void CreateSimplePdf(string filePath, string content)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(content);
        pdf.SaveAs(filePath);
    }
}
Imports IronPdf
Public Class PdfGenerator
	Public Shared Sub CreateSimplePdf(ByVal filePath As String, ByVal content As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf = renderer.RenderHtmlAsPdf(content)
		pdf.SaveAs(filePath)
	End Sub
End Class
$vbLabelText   $csharpLabel

このコードでは、IronPDF のChromePdfRenderer クラスを使用して HTML コンテンツを PDF としてレンダリングし、ファイルに保存します。

Bouncy Castleを使用してPDFを暗号化

PDFを生成した後、Bouncy Castleを使用してそれを暗号化できます。 ここでは、EncryptDataメソッドをPDFファイルに対応するように修正します:

// ... [Previous Bouncy Castle using statements]
public class PdfEncryption
{
    public static void EncryptPdfFile(string inputFilePath, string outputFilePath, string password)
    {
        // Read the PDF file
        byte[] pdfBytes = File.ReadAllBytes(inputFilePath);
        // Encrypt the PDF bytes
        byte[] encryptedBytes = SimpleEncryption.EncryptData(Encoding.UTF8.GetString(pdfBytes), password);
        // Write the encrypted bytes to a new file
        File.WriteAllBytes(outputFilePath, encryptedBytes);
    }
}
// ... [Previous Bouncy Castle using statements]
public class PdfEncryption
{
    public static void EncryptPdfFile(string inputFilePath, string outputFilePath, string password)
    {
        // Read the PDF file
        byte[] pdfBytes = File.ReadAllBytes(inputFilePath);
        // Encrypt the PDF bytes
        byte[] encryptedBytes = SimpleEncryption.EncryptData(Encoding.UTF8.GetString(pdfBytes), password);
        // Write the encrypted bytes to a new file
        File.WriteAllBytes(outputFilePath, encryptedBytes);
    }
}
' ... [Previous Bouncy Castle using statements]
Public Class PdfEncryption
	Public Shared Sub EncryptPdfFile(ByVal inputFilePath As String, ByVal outputFilePath As String, ByVal password As String)
		' Read the PDF file
		Dim pdfBytes() As Byte = File.ReadAllBytes(inputFilePath)
		' Encrypt the PDF bytes
		Dim encryptedBytes() As Byte = SimpleEncryption.EncryptData(Encoding.UTF8.GetString(pdfBytes), password)
		' Write the encrypted bytes to a new file
		File.WriteAllBytes(outputFilePath, encryptedBytes)
	End Sub
End Class
$vbLabelText   $csharpLabel

このメソッドでは、PDFファイルをバイトとして読み込み、以前に定義したSimpleEncryptionクラスを使用してこれらのバイトを暗号化し、その後、暗号化されたバイトを新しいファイルに書き込みます。

結論

BouncyCastle C# (開発者にとっての動作方法): 図5 - IronPDF ライセンス情報

結論として、Bouncy Castle C#とIronPDFを組み合わせることで、.NETアプリケーションにおいてPDFドキュメントの作成およびセキュリティ確保のためのソリューションを提供します。 Bouncy Castleはデータのセキュリティを確保するために必要な暗号化ツールを提供し、IronPDFはPDFの作成と操作の簡便さをもたらします。 この統合は、高度な文書のセキュリティと機密性が要求されるシナリオにおいて特に価値があります。

IronPDFに興味のある開発者のために、ライブラリは無料のトライアルバージョンを提供しています。 IronPDFを本番環境に統合することを決定した場合は、ライセンス情報とオプションが利用可能です。

チペゴ
ソフトウェアエンジニア
チペゴは優れた傾聴能力を持ち、それが顧客の問題を理解し、賢明な解決策を提供する助けとなっています。彼は情報技術の学士号を取得後、2023年にIron Softwareチームに加わりました。現在、彼はIronPDFとIronOCRの2つの製品に注力していますが、顧客をサポートする新しい方法を見つけるにつれて、他の製品に関する知識も日々成長しています。Iron Softwareでの協力的な生活を楽しんでおり、さまざまな経験を持つチームメンバーが集まり、効果的で革新的な解決策を提供することに貢献しています。チペゴがデスクを離れているときは、良い本を楽しんだり、サッカーをしていることが多いです。
< 以前
C# 文字列補間(開発者向け解説)
次へ >
Math.NET C#(開発者向けの仕組み)