首页 > 编程语言 >.net中加解密用BouncyCastle就够了,支持常用的各种加密解密算法

.net中加解密用BouncyCastle就够了,支持常用的各种加密解密算法

时间:2023-12-10 09:23:11浏览次数:38  
标签:BouncyCastle string using 加解密 就够 input new byte

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 的官方文档以获取最新信息。

标签:BouncyCastle,string,using,加解密,就够,input,new,byte
From: https://www.cnblogs.com/hanbing81868164/p/17892182.html

相关文章

  • vue+spirngboot前后端数据加解密(基于AES+RSA实现)
    案例说明案例只针对post请求这里使用’Content-Type’:‘application/x-www-form-urlencoded;charset=UTF-8’;为键值对的形式(非json)AES加密数据,RAS加密AES的key实现思路前台首先请求非加密接口获取后台的公钥前台在请求前生成自己的公钥和私钥,以及AES对称加密的key使用前台......
  • Markdown最全基本语法整理 - 有这一篇就够了
    参考:Markdown最全基本语法整理-有这一篇就够了-郭炫韩Coding-博客园(cnblogs.com)    《一》什么是MarkdownMarkdown是一种轻量级的标记语言,它允许人们使用易读易写的纯文本格式编写文档,借助可实现快速排版且转换成格式丰富的HTML页面。目前被越来越多的写作爱好......
  • 扫盲Kafka?看这一篇就够了!【转】
     kafka的使用场景为什么要使用Kafka消息队列?解耦、削峰:传统的方式上游发送数据下游需要实时接收,如果上游在某些业务场景:例如上午十点会流量激增至顶峰,那么下游资源可能会扛不住压力。但如果使用消息队列,就可以将消息暂存在消息管道中,下游可以按照自己的速度逐步处理;可扩展:......
  • 【实用+干货】如何使用Clickhouse搭建百亿级用户画像平台看这一篇就够了
    背景如果你是用户,当你使用抖音、小红书的时候,假如平台能根据你的属性、偏好、行为推荐给你感兴趣的内容,那就能够为你节省大量获取内容的时间。如果你是商家,当你要进行广告投放的时候,假如平台推送的用户都是你潜在的买家,那你就可以花更少的钱,带来更大的收益。这两者背后都有一项......
  • .net中优秀依赖注入框架Autofac看一篇就够了
    Autofac是一个功能丰富的.NET依赖注入容器,用于管理对象的生命周期、解决依赖关系以及进行属性注入。本文将详细讲解Autofac的使用方法,包括多种不同的注册方式,属性注入,以及如何使用多个 ContainerBuilder 来注册和合并组件。我们将提供详细的源代码示例来说明每个概念。1......
  • .net中优秀依赖注入框架Autofac看一篇就够了
     Autofac是一个功能丰富的.NET依赖注入容器,用于管理对象的生命周期、解决依赖关系以及进行属性注入。本文将详细讲解Autofac的使用方法,包括多种不同的注册方式,属性注入,以及如何使用多个 ContainerBuilder 来注册和合并组件。我们将提供详细的源代码示例来说明每个概念......
  • C++ CryptoPP使用AES加解密
    Crypto++(CryptoPP)是一个用于密码学和加密的C++库。它是一个开源项目,提供了大量的密码学算法和功能,包括对称加密、非对称加密、哈希函数、消息认证码(MAC)、数字签名等。Crypto++的目标是提供高性能和可靠的密码学工具,以满足软件开发中对安全性的需求。高级加密标准(Advanc......
  • netty服务端加解密
    参考链接:https://www.cnblogs.com/silyvin/articles/11827030.html一、解密1、自定义解密类importio.netty.buffer.ByteBuf;importio.netty.buffer.Unpooled;importio.netty.channel.ChannelHandlerContext;importio.netty.handler.codec.ByteToMessageDecoder;impor......
  • yum源配置,看这一篇就够了!
    yum源是什么yum(全称YellowDogUpdater)是一个在Fedora和RedHat以及CentOS中的Shell前端软件包管理器。基于RPM包管理,能够从指定的服务器自动下载RPM包并且安装,可以自动处理包之间的依赖关系,并且一次安装所有依赖的软件包。yum源的作用yum源是Linux系统中的软件管理仓库,可以完......
  • 字字珠玑,想了解Cocos Creator项目结构,看这篇就够了
    一、项目文件夹结构初次创建并打开一个CocosCreator项目后,开发者的项目文件夹将会包括以下结构: 下面我们将会介绍每个文件夹的功能。1.资源文件夹(assets)assets将会用来放置游戏中所有的本地资源、脚本和第三方库文件。只有在assets目录下的内容才能显示在资源管理器中......