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

时间:2023-03-28
本文介绍了如何在 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# 中使用公钥和私钥加密技术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:RSACryptoServiceProvider 用自己的公钥和私钥初始化 下一篇:Rfc2898/PBKDF2 与 SHA256 作为 C# 中的摘要

相关文章