C#RSA非对称加解密

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.Globalization;
using System.IO;

/// <summary>
///RSA 的摘要说明
/// </summary>
public class RSA
{
 public RSA()
 {
  //
  //TODO: 在此处添加构造函数逻辑
  //

 }
 #region RSA非对称加解密  密钥保存在密钥容器,密钥容器保存在计算机的密钥库中

 //public static RSACryptoServiceProvider rsa;
 //static byte[] cipherbytes;//密码字节
 //static string PublicAndPrivateKey = null; //私鈅变量
 //static string PublicKey = null; //公钥变量

 static RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
 //static RSAParameters rsaParamsExcludePrivate = rsa.ExportParameters(false);
 //static RSAParameters rsaParamsIncludePrivate = rsa.ExportParameters(true);

 static string PPKey; //私鈅变量
 static string PKey; //公钥变量


 

 private static void CreateRSAcsp()
 {
   //实例化CspParameters对象

   CspParameters cspPara = new CspParameters();

   //指定CspParameters对象实例的名称

   cspPara.KeyContainerName = "key_container_test";

   //设置密钥类型为Exchange

   cspPara.KeyNumber = 1;

   //设置密钥容器保存到计算机密钥库(默认为用户密钥库)

   cspPara.Flags = CspProviderFlags.UseMachineKeyStore;

   //实例化RSA对象的时候,将CspParameters对象作为构造函数的参数传递给RSA对象,

   //如果名称为key_container_test的密钥容器不存在,RSA对象会创建这个密钥容器;

   //如果名称为key_container_test的密钥容器已经存在,RSA对象会使用这个密钥容器中的密钥进行实例化

   //RSACryptoServiceProvider rsaPro = new RSACryptoServiceProvider(cspPara);

   rsa = new RSACryptoServiceProvider(cspPara);
 }


 /// <summary>
 /// RSA加密
 /// </summary>
 /// <param name="EnStr">要加密的字符串</param>
 /// <returns></returns>
 public static string RSAEncrypt1(string EnStr)
 {
  
  CreateRSAcsp();
  RSACryptoServiceProvider _rsa = new RSACryptoServiceProvider();  
  _rsa.ImportParameters(rsa.ExportParameters(false));//导入公钥  
  byte[] byteData = Encoding.UTF8.GetBytes(EnStr);
  byte[] EncryptedData = rsa.Encrypt(byteData, false);
  string result = BitConverter.ToString(EncryptedData);
  return result;
 }

 /// <summary>
 /// RSA解密
 /// </summary>
 /// <param name="EeStr">要解密密的字符串</param>
 /// <returns></returns>
 public static string RSADecrypt1(string EeStr)
 {
  
  string[] sInput = EeStr.Split("-".ToCharArray());
  byte[] data = new byte[sInput.Length];
  for (int i = 0; i < sInput.Length; i++)
  {
   data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
  }
  CreateRSAcsp();
  rsa.ImportParameters(rsa.ExportParameters(true)); //导入私钥
  byte[] DecryptedData = rsa.Decrypt(data, false);
  string str = string.Empty;
  str = Encoding.UTF8.GetString(DecryptedData);
  return str;
 }

 #endregion

 

 


 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
双向 RSA + AES 加密是一种常见的加密方式,其中使用 RSA 算法加密 AES 密钥,然后使用 AES 算法加密数据。在 C# 中,可以使用 `RSACryptoServiceProvider` 类和 `AesCryptoServiceProvider` 类来实现此加密方式。以下是一个简单的示例: ```csharp using System; using System.IO; using System.Security.Cryptography; using System.Text; class Program { static void Main(string[] args) { string plainText = "Hello, world!"; byte[] encryptedData = Encrypt(plainText); string decryptedText = Decrypt(encryptedData); Console.WriteLine("Original text: {0}", plainText); Console.WriteLine("Encrypted data: {0}", Convert.ToBase64String(encryptedData)); Console.WriteLine("Decrypted text: {0}", decryptedText); } static byte[] Encrypt(string plainText) { byte[] aesKey = GenerateAesKey(); using (var rsa = new RSACryptoServiceProvider()) { rsa.PersistKeyInCsp = false; byte[] encryptedAesKey = rsa.Encrypt(aesKey, true); // 使用 RSA 加密 AES 密钥 using (var aes = new AesCryptoServiceProvider()) { aes.Key = aesKey; aes.GenerateIV(); using (var memoryStream = new MemoryStream()) { memoryStream.Write(aes.IV, 0, aes.IV.Length); using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { byte[] plainData = Encoding.UTF8.GetBytes(plainText); cryptoStream.Write(plainData, 0, plainData.Length); cryptoStream.FlushFinalBlock(); } byte[] encryptedData = memoryStream.ToArray(); byte[] result = new byte[encryptedAesKey.Length + encryptedData.Length]; Buffer.BlockCopy(encryptedAesKey, 0, result, 0, encryptedAesKey.Length); Buffer.BlockCopy(encryptedData, 0, result, encryptedAesKey.Length, encryptedData.Length); return result; } } } } static string Decrypt(byte[] encryptedData) { byte[] encryptedAesKey = new byte[128]; // RSA 加密 AES 密钥得到的密文长度为 128 字节 byte[] encryptedDataOnly = new byte[encryptedData.Length - encryptedAesKey.Length]; Buffer.BlockCopy(encryptedData, 0, encryptedAesKey, 0, encryptedAesKey.Length); Buffer.BlockCopy(encryptedData, encryptedAesKey.Length, encryptedDataOnly, 0, encryptedDataOnly.Length); using (var rsa = new RSACryptoServiceProvider()) { rsa.PersistKeyInCsp = false; byte[] aesKey = rsa.Decrypt(encryptedAesKey, true); // 使用 RSA 解密 AES 密钥 using (var aes = new AesCryptoServiceProvider()) { aes.Key = aesKey; aes.IV = encryptedDataOnly.Take(aes.IV.Length).ToArray(); using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(encryptedDataOnly, aes.IV.Length, encryptedDataOnly.Length - aes.IV.Length); cryptoStream.FlushFinalBlock(); } byte[] decryptedData = memoryStream.ToArray(); return Encoding.UTF8.GetString(decryptedData); } } } } static byte[] GenerateAesKey() { using (var aes = new AesCryptoServiceProvider()) { aes.GenerateKey(); return aes.Key; } } } ``` 上面的代码中,首先调用 `GenerateAesKey` 方法生成 AES 密钥,然后使用 RSA 算法加密 AES 密钥。加密时,先将 AES 密钥使用 RSA 加密,然后使用 AES 算法加密数据。具体来说,将 AES 密钥和 IV 都写入 `MemoryStream` 对象中,然后使用 `CryptoStream` 对象将数据写入 `MemoryStream` 对象中。最后将密文和 RSA 加密的 AES 密钥一起返回。 解密时,先从密文中取出 RSA 加密的 AES 密钥,然后使用 RSA 算法解密 AES 密钥。解密时,先从密文中取出 AES 的 IV 值,然后使用 `CryptoStream` 对象将数据解密。最后将解密后的文本返回。 注意,上面的示例仅用于演示 RSA + AES 加密的基本原理,实际使用中还需要考虑安全性等因素。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东云180

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值