如何在 C# 中使用公钥和私钥加密技术

How to use public and private key encryption technique in C#(如何在 C# 中使用公钥和私钥加密技术)
本文介绍了如何在 C# 中使用公钥和私钥加密技术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想使用公钥/私钥技术加密数据.我的意思是,用接收者的公钥加密,接收者可以用自己的私钥解密.

I want to encrypt data using public/private key technique. I mean, encrypt with the public key of receiver and the receiver can decrypt with their own private key.

我该怎么做?您有什么建议或示例代码吗?

How can I do that? Do you have any suggestion or sample code ?

推荐答案

代码示例:

private static string _privateKey;
private static string _publicKey;
private static UnicodeEncoding _encoder = new UnicodeEncoding();

private static void RSA()
{
  var rsa = new RSACryptoServiceProvider();
  _privateKey = rsa.ToXmlString(true);
  _publicKey = rsa.ToXmlString(false);

  var text = "Test1";
  Console.WriteLine("RSA // Text to encrypt: " + text);
  var enc = Encrypt(text);
  Console.WriteLine("RSA // Encrypted Text: " + enc);
  var dec = Decrypt(enc);
  Console.WriteLine("RSA // Decrypted Text: " + dec);
}

public static string Decrypt(string data)
{
  var rsa = new RSACryptoServiceProvider();
  var dataArray = data.Split(new char[] { ',' });
  byte[] dataByte = new byte[dataArray.Length];
  for (int i = 0; i < dataArray.Length; i++)
  {
    dataByte[i] = Convert.ToByte(dataArray[i]);
  }

  rsa.FromXmlString(_privateKey);
  var decryptedByte = rsa.Decrypt(dataByte, false);
  return _encoder.GetString(decryptedByte);
}

public static string Encrypt(string data)
{
  var rsa = new RSACryptoServiceProvider();
  rsa.FromXmlString(_publicKey);
  var dataToEncrypt = _encoder.GetBytes(data);
  var encryptedByteArray = rsa.Encrypt(dataToEncrypt, false).ToArray();
  var length = encryptedByteArray.Count();
  var item = 0;
  var sb = new StringBuilder();
  foreach (var x in encryptedByteArray)
  {
    item++;
    sb.Append(x);

    if (item < length)
      sb.Append(",");
  }

  return sb.ToString();
}

这篇关于如何在 C# 中使用公钥和私钥加密技术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Custom Error Queue Name when using EasyNetQ for RabbitMQ?(使用 EasyNetQ for RabbitMQ 时自定义错误队列名称?)
How to generate password_hash for RabbitMQ Management HTTP API(如何为 RabbitMQ 管理 HTTP API 生成密码哈希)
Rabbitmq Ack or Nack, leaving messages on the queue(Rabbitmq Ack 或 Nack,将消息留在队列中)
Setup RabbitMQ consumer in ASP.NET Core application(在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者)
Specify Publish timeouts in mass transit(指定公共交通中的发布超时)
RabbitMQ asynchronous support(RabbitMQ 异步支持)