.NET ヘルプ

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

更新済み 1月 14, 2024
共有:

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

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をC#プロジェクトに統合してください。 これは通常、プロジェクト設定にライブラリを参照として追加することを含みます。

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

BouncyCastle C#(開発者向けの動作原理):図1 - NuGet パッケージ マネージャーの検索バーで「Bouncycastle」を検索し、NuGet パッケージ マネージャーを使用して Bouncy Castle をダウンロードおよびインストールする

基本的な暗号化の例

この例では、AESを使用した簡単な暗号化シナリオを示します。 (高度暗号化標準) C#でBouncy Castleを使用する

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
VB   C#

このコードスニペットは、基本的な暗号化方法の作成方法を示しています。 実装のセキュリティを確保するために、発生する可能性のある例外を適切に処理することが重要です。 このメソッドを使用するには、暗号化したいメッセージとパスワードを指定して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))
VB   C#

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

BouncyCastle C# (バウンシーキャッスル C#) (開発者向けの動作方法): 図2 - コンソール出力

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

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

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

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

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

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

Bouncy CastleとIronPDFの統合

BouncyCastle C#(開発者向けの働き方):図3 - IronPDF for .NET: The C# PDF Library

IronPDF Bouncy Castleの機能を補完し、PDFドキュメントを扱う機能を提供します。これにより、Bouncy Castleの暗号化機能を使用してPDFドキュメントを保護することができます。 以下のようにして、これら2つの強力なライブラリを統合できます。

IronPDFの注目すべき機能はその HTMLからPDF すべてのレイアウトとスタイルを保持する能力。 ウェブコンテンツをPDFに変換し、レポート、請求書、およびドキュメントに適しています。 HTMLファイル、URL、およびHTML文字列をシームレスに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");
    }
}
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
VB   C#

IronPDFライブラリのインストール

PDF 用 C# NuGet ライブラリ

でインストール NuGet

Install-Package IronPdf
または
Java PDF JAR(ジャバPDF JAR)

ダウンロード DLL (ディーエルエル)

DLLをダウンロード

プロジェクトに手動でインストールする

PDF 用 C# NuGet ライブラリ

でインストール NuGet

Install-Package IronPdf
または
Java PDF JAR(ジャバPDF JAR)

ダウンロード DLL (ディーエルエル)

DLLをダウンロード

プロジェクトに手動でインストールする

今日からプロジェクトでIronPDFを使い始めましょう。無料のトライアルをお試しください。

最初のステップ:
green arrow pointer

チェックアウト IronPDF オン Nuget 迅速なインストールと展開のために。8百万以上のダウンロード数により、PDFをC#で変革しています。

PDF 用 C# NuGet ライブラリ nuget.org/packages/IronPdf/
Install-Package IronPdf

インストールを検討してください IronPDF DLL 直接。ダウンロードして、プロジェクトまたはGACの形式で手動でインストールしてください。 IronPdf.zip

プロジェクトに手動でインストールする

DLLをダウンロード

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

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

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

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

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

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

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

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

Install-Package IronPdf

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

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

IronPDFの詳細な概要、機能、互換性、および追加のダウンロードオプションについては、NuGetウェブサイトのIronPDFページ をご覧ください。

DLLを使ってインストール

代わりに、IronPDFのdllファイルをプロジェクトに直接組み込むことができます。DLLを含むZIPファイルを次のリンクからダウンロードしてください リンク. 解凍して、プロジェクトにDLLを含めてください。

IronPDFを使用したPDFの生成

まずは シンプルなPDFドキュメントを作成する using IronPDF:

using IronPDF

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
VB   C#

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

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

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

// ... [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
VB   C#

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

結論

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

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

探求に興味がある方へ IronPDF, 開発者がその機能を試して評価することを可能にしています。 本番環境にIronPDFを導入することを決定した場合、ライセンスは$749から始まります。

< 以前
C#の文字列補間(開発者向けの仕組み)
次へ >
Math.NET C#(開発者向け動作方法)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >