.net中加解密用BouncyCastle就夠了,支持常用的各種加密解密演算法

来源:https://www.cnblogs.com/hanbing81868164/archive/2023/12/10/17892182.html
-Advertisement-
Play Games

BouncyCastle 是一個流行的 Java 加解密庫,也支持在 .NET 平臺上使用。下麵是 BouncyCastle 在 .NET 下使用的一些常見功能,包括 AES、RSA、MD5、SHA1、DES、SHA256、SHA384、SHA512 等。 在開始之前,請確保你已經將 BouncyC ...


BouncyCastle 是一個流行的 Java 加解密庫,也支持在 .NET 平臺上使用。下麵是 BouncyCastle 在 .NET 下使用的一些常見功能,包括 AES、RSA、MD5、SHA1、DES、SHA256、SHA384、SHA512 等。

在開始之前,請確保你已經將 BouncyCastle 的 NuGet 包安裝到你的項目中。你可以通過 NuGet 包管理器控制台或 Visual Studio 中的 NuGet 包管理器進行安裝。

Install-Package BouncyCastle

接下來,我將演示如何使用 BouncyCastle 實現一些常見的加解密操作。

1. AES 加解密

using System;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;

public class AesExample
{
    public static byte[] Encrypt(string plaintext, byte[] key, byte[] iv)
    {
        CipherEngine engine = new CipherEngine();
        CipherParameters keyParam = new KeyParameter(key);
        ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv);

        engine.Init(true, keyParamWithIV);

        byte[] input = Encoding.UTF8.GetBytes(plaintext);
        byte[] output = new byte[engine.GetOutputSize(input.Length)];

        int len = engine.ProcessBytes(input, 0, input.Length, output, 0);
        engine.DoFinal(output, len);

        return output;
    }

    public static string Decrypt(byte[] ciphertext, byte[] key, byte[] iv)
    {
        CipherEngine engine = new CipherEngine();
        CipherParameters keyParam = new KeyParameter(key);
        ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv);

        engine.Init(false, keyParamWithIV);

        byte[] output = new byte[engine.GetOutputSize(ciphertext.Length)];

        int len = engine.ProcessBytes(ciphertext, 0, ciphertext.Length, output, 0);
        engine.DoFinal(output, len);

        return Encoding.UTF8.GetString(output);
    }
}

// 示例用法
byte[] aesKey = new byte[16]; // AES 128-bit key
byte[] aesIV = new byte[16];  // AES 128-bit IV
string plaintext = "Hello, BouncyCastle!";

byte[] ciphertext = AesExample.Encrypt(plaintext, aesKey, aesIV);
string decryptedText = AesExample.Decrypt(ciphertext, aesKey, aesIV);

Console.WriteLine($"Plaintext: {plaintext}");
Console.WriteLine($"Ciphertext: {Convert.ToBase64String(ciphertext)}");
Console.WriteLine($"Decrypted Text: {decryptedText}");

2. RSA 加解密

using System;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;

public class RsaExample
{
    public static byte[] Encrypt(string plaintext, AsymmetricKeyParameter publicKey)
    {
        CipherEngine engine = new CipherEngine();
        engine.Init(true, publicKey);

        byte[] input = Encoding.UTF8.GetBytes(plaintext);
        byte[] output = engine.ProcessBytes(input, 0, input.Length);

        return output;
    }

    public static string Decrypt(byte[] ciphertext, AsymmetricKeyParameter privateKey)
    {
        CipherEngine engine = new CipherEngine();
        engine.Init(false, privateKey);

        byte[] output = engine.ProcessBytes(ciphertext, 0, ciphertext.Length);

        return Encoding.UTF8.GetString(output);
    }
}

// 示例用法
RsaKeyPairGenerator rsaKeyPairGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
rsaKeyPairGen.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); // 2048-bit key size
AsymmetricCipherKeyPair keyPair = rsaKeyPairGen.GenerateKeyPair();

AsymmetricKeyParameter publicKey = keyPair.Public;
AsymmetricKeyParameter privateKey = keyPair.Private;

string plaintext = "Hello, BouncyCastle!";

byte[] ciphertext = RsaExample.Encrypt(plaintext, publicKey);
string decryptedText = RsaExample.Decrypt(ciphertext, privateKey);

Console.WriteLine($"Plaintext: {plaintext}");
Console.WriteLine($"Ciphertext: {Convert.ToBase64String(ciphertext)}");
Console.WriteLine($"Decrypted Text: {decryptedText}");

3. MD5、SHA1、SHA256、SHA384、SHA512

using System;
using System.Security.Cryptography;
using System.Text;
using Org.BouncyCastle.Crypto.Digests;

public class HashExample
{
    public static string ComputeMD5(string input)
    {
        MD5 md5 = MD5.Create();
        byte[] hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
        return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
    }

    public static string ComputeSHA1(string input)
    {
        SHA1 sha1 = SHA1.Create();
        byte[] hashBytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
        return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
    }

    public static string ComputeSHA256(string input)
    {
        Sha256Digest sha256 = new Sha256Digest();
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);
        sha256.BlockUpdate(inputBytes, 0, inputBytes.Length);

        byte[] hashBytes = new byte[sha256.GetDigestSize()];
        sha256.DoFinal(hashBytes, 0);

        return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
    }

    public static string ComputeSHA384(string input)
    {
        Sha384Digest sha384 = new Sha384Digest();
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);
        sha384.BlockUpdate(inputBytes, 0, inputBytes.Length);

        byte[] hashBytes = new byte[sha384.GetDigestSize()];
        sha384.DoFinal(hashBytes, 0);

        return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
    }

    public static string ComputeSHA512(string input)
    {
        Sha512Digest sha512 = new Sha512Digest();
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);
        sha512.BlockUpdate(inputBytes, 0, inputBytes.Length);

        byte[] hashBytes = new byte[sha512.GetDigestSize()];
        sha512.DoFinal(hashBytes, 0);

        return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
    }
}

// 示例用法
string input = "Hello, BouncyCastle!";
Console.WriteLine($"MD5: {HashExample.ComputeMD5(input)}");
Console.WriteLine($"SHA1: {HashExample.ComputeSHA1(input)}");
Console.WriteLine($"SHA256: {HashExample.ComputeSHA256(input)}");
Console.WriteLine($"SHA384: {HashExample.ComputeSHA384(input)}");
Console.WriteLine($"SHA512: {HashExample.ComputeSHA512(input)}");

這些示例展示了在 .NET 下使用 BouncyCastle 實現 AES、RSA、MD5、SHA1、SHA256、SHA384、SHA512 加解密的基本操作。

具體的實現細節可能根據 BouncyCastle 版本略有變化,建議查閱 BouncyCastle 的官方文檔以獲取最新信息。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 最近想著把工作中使用過的java命令都梳理一下,方便日後查閱。雖然這類文章很多,但自己梳理總結後,還是會有一些新的收穫。這也是這篇筆記的由來。 ...
  • SCG(Spring Cloud Gateway)就我個人理解,是想讓開發者把它作為一個較為簡單的網關框架,只需簡單在yml文件中寫幾個配置項就可以運行。所以它不大推薦在網關這一層獲取body數據或者做一下複雜的業務處理。故而在實際編寫代碼中,獲取queryParam很容易,但body數據就比較麻煩 ...
  • 1 Python解釋器下載 1.1 安裝環境 Windows 10 專業工作站版22H2 python-3.9.6-amd64.exe 1.2 下載地址 Python官網:https://www.python.org/ Python鏡像:https://registry.npmmirror.com/ ...
  • 當我們談論編程中的數據結構時,順序容器是不可忽視的一個重要概念。順序容器是一種能夠按照元素添加的順序來存儲和檢索數據的數據結構。它們提供了簡單而直觀的方式來組織和管理數據,為程式員提供了靈活性和性能的平衡。Qt 中提供了豐富的容器類,用於方便地管理和操作數據。這些容器類涵蓋了各種不同的用途,從簡單的... ...
  • 操作系統 :CentOS 7.6_x64 Python版本:3.9.12 MySQL版本:5.7.38 日常開發過程中,會遇到mysql數據表的備份需求,需要針對單獨的數據表進行備份並定時清理數據。 今天記錄下python3如何使用pandas進行mysql數據表的備份,我將從以下幾個方面進行展開: ...
  • 限制結果 您可以通過使用"LIMIT"語句來限制查詢返回的記錄數量。以下是一個示例,獲取您自己的Python伺服器中"customers"表中的前5條記錄: import mysql.connector mydb = mysql.connector.connect( host="localhost" ...
  • ASP.NET Core 8 在 Windows 上各種部署模型的性能測試 我們知道 Asp.net Core 在 windows 伺服器上部署的方案有 4 種之多。這些部署方案對性能的影響一直以來都是靠經驗。比如如果是部署在 IIS 下,那麼 In Process 會比 Out Process 快 ...
  • 一年又快結束,疫情似乎已經離去,但是最近的感冒又讓人感受到了一絲不安~ 回顧著過往幾年,一個詞形容:渾渾噩噩。 總結著 2023 年,有開心,有憧憬,有遺憾,有成長,但如果用一個詞的話,我覺得是:尋找 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...