C#中RSA加密解密

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#中RSA加密解密相关的知识,希望对你有一定的参考价值。

麻烦大家 给我找些 相关的示例Demo

代码 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace MyRSA

public class MyRSA


private static string publicKey = "<RSAKeyValue><Modulus>6CdsXgYOyya/yQHTO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5LwPycZwtNOx3Cfy44/D5Mj86koPew5soFIz9sxPAHRF5hcqJoG+q+UfUYTHYCsMH2cnqGVtnQiE/PMRMmY0RwEfMIo+TDpq3QyO03MaEsDGf13sPw9YRXiac=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
private static string privateKey = "<RSAKeyValue><Modulus>6CdsXgYOyya/yQHTO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5LwPycZwtNOx3Cfy44/D5Mj86koPew5soFIz9sxPAHRF5hcqJoG+q+UfUYTHYCsMH2cnqGVtnQiE/PMRMmY0RwEfMIo+TDpq3QyO03MaEsDGf13sPw9YRXiac=</Modulus><Exponent>AQAB</Exponent><P>/aoce2r6tonjzt1IQI6FM4ysR40j/gKvt4dL411pUop1Zg61KvCm990M4uN6K8R/DUvAQdrRdVgzvvAxXD7ESw==<Q>6kqclrEunX/fmOleVTxG4oEpXY4IJumXkLpylNR3vhlXf6ZF9obEpGlq0N7sX2HBxa7T2a0WznOAb0si8FuelQ==</Q><DP>3XEvxB40GD5v/Rr4BENmzQW1MBFqpki6FUGrYiUd2My+iAW26nGDkUYMBdYHxUWYlIbYo6Tezc3d/oW40YqJ2Q==</DP><DQ>LK0XmQCmY/ArYgw2Kci5t51rluRrl4f5l+aFzO2K+9v3PGcndjAStUtIzBWGO1X3zktdKGgCLlIGDrLkMbM21Q==</DQ><InverseQ>GqC4Wwsk2fdvJ9dmgYlej8mTDBWg0Wm6aqb5kjncWK6WUa6CfD+XxfewIIq26+4Etm2A8IAtRdwPl4aPjSfWdA==</InverseQ><D>a1qfsDMY8DSxB2DCr7LX5rZHaZaqDXdO3GC01z8dHjI4dDVwOS5ZFZs7MCN3yViPsoRLccnVWcLzOkSQF4lgKfTq3IH40H5N4gg41as9GbD0g9FC3n5IT4VlVxn9ZdW+WQryoHdbiIAiNpFKxL/DIEERur4sE1Jt9VdZsH24CJE=</D></RSAKeyValue>";

static public string Decrypt(string base64code)

try


//Create a UnicodeEncoder to convert between byte array and string.
UnicodeEncoding ByteConverter = new UnicodeEncoding();

//Create a new instance of RSACryptoServiceProvider to generate
//public and private key data.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.FromXmlString(privateKey);

byte[] encryptedData;
byte[] decryptedData;
encryptedData = Convert.FromBase64String(base64code);

//Pass the data to DECRYPT, the private key information
//(using RSACryptoServiceProvider.ExportParameters(true),
//and a boolean flag specifying no OAEP padding.
decryptedData = RSADecrypt(encryptedData, RSA.ExportParameters(true), false);

//Display the decrypted plaintext to the console.
return ByteConverter.GetString(decryptedData);

catch (Exception exc)

//Exceptions.LogException(exc);
Console.WriteLine(exc.Message);
return "";



static public string Encrypt(string toEncryptString)

try

//Create a UnicodeEncoder to convert between byte array and string.
UnicodeEncoding ByteConverter = new UnicodeEncoding();

//Create byte arrays to hold original, encrypted, and decrypted data.
byte[] dataToEncrypt = ByteConverter.GetBytes(toEncryptString);
byte[] encryptedData;
byte[] decryptedData;

//Create a new instance of RSACryptoServiceProvider to generate
//public and private key data.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

RSA.FromXmlString(privateKey);

//Pass the data to ENCRYPT, the public key information
//(using RSACryptoServiceProvider.ExportParameters(false),
//and a boolean flag specifying no OAEP padding.
encryptedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(false), false);

string base64code = Convert.ToBase64String(encryptedData);
return base64code;

catch (Exception exc)

//Catch this exception in case the encryption did
//not succeed.
//Exceptions.LogException(exc);
Console.WriteLine(exc.Message);
return "";




static private byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)

try

//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

//Import the RSA Key information. This only needs
//toinclude the public key information.
RSA.ImportParameters(RSAKeyInfo);

//Encrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);

//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)

//Exceptions.LogException(e);
Console.WriteLine(e.Message);

return null;




static private byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)

try

//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

//Import the RSA Key information. This needs
//to include the private key information.
RSA.ImportParameters(RSAKeyInfo);

//Decrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);

//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)

//Exceptions.LogException(e);
Console.WriteLine(e.Message);

return null;







测试代码: static void Main(string[] args)

string encodeString = MyRSA.Encrypt("1234567");
Console.WriteLine(encodeString);

string decode = MyRSA.Decrypt(encodeString);
Console.WriteLine(decode);

Console.ReadLine();
参考技术A 这是一个加密解密文件的例子,你看看吧! private string Encrypt(string s)

Encoding ascii = Encoding.ASCII;
string EncrytString;
EncrytString = ""; for (int i = 0; i < s.Length; i++)

int j;
byte[] b = new byte[1];
j = Convert.ToInt32(ascii.GetBytes(s[i].ToString())[0]);
j = j + 1;
b[0] = Convert.ToByte(j);
EncrytString = EncrytString + ascii.GetString(b);

return EncrytString;
//解密
private string Decryptor(string s)

Encoding ascii = Encoding.ASCII;
string DencrytString;
DencrytString = ""; for (int i = 0; i < s.Length; i++)

int j;
byte[] b = new byte[1];
j = Convert.ToInt32(ascii.GetBytes(s[i].ToString())[0]);
j=j-1;
b[0]=Convert.ToByte(j);
DencrytString = DencrytString+ascii.GetString(b);

return DencrytString;
//加密文件
private void button1_Click(object sender, EventArgs e)

this.richTextBox1.Clear();
this.openFileDialog1.ShowDialog();
this.textBox1.Text = this.openFileDialog1.FileName; StreamReader sr = new StreamReader(openFileDialog1.FileName);
string text; //加密方法
text = Encrypt( sr.ReadToEnd());
this.richTextBox1.Text = text;
sr.Close();
/// <summary>
/// 解密
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)

string dstring;
dstring = Decryptor(this.richTextBox1.Text);
this.richTextBox1.Text = dstring;
参考技术B http://blog.csdn.net/llwinnner/archive/2009/03/21/4011936.aspx自己看吧

使用预先存在的 RSA SSH 密钥解密 C# 中的文本

【中文标题】使用预先存在的 RSA SSH 密钥解密 C# 中的文本【英文标题】:Use preexisting RSA SSH keys to decrypt a text in C# 【发布时间】:2013-04-11 13:10:51 【问题描述】:

我有一对由 Linux 计算机中的“ssh-keygen”命令生成的 RSA 公钥/私钥。这台 Linux 计算机中有一个 Ruby 应用程序,它使用这个公钥加密一个字符串,我想用这个私钥解密 Windows C#/.Net 应用程序中的字符串。我看了一下 Bouncy Castle 库,但没有成功。任何示例或提示都会有所帮助。谢谢!

【问题讨论】:

SSH 中的 RSA 密钥仅用于对数据进行签名以验证身份,而不用于加密会话数据甚至交换会话密钥。使用它们来加密数据并不是最佳实践。 【参考方案1】:

有理由使用 ssh 密钥吗?

任何 RSA 密钥都足够了。您需要提取 RSA 密钥来加密任何内容。如果该密钥不是 RSA,则您无法加密任何内容,因为 DSA 是仅签名算法。有公钥的 RFC:http://www.ietf.org/rfc/rfc4716.txt 这不是您所需要的。但可能会帮助您了解如何提取每个部分。它应该只是 base64 编码的二进制块。

你可以试试 PuTTY 源码http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html keygen 可以生成和转换这些密钥。所以,如果你找到它提取 RSA 密钥的地方。然后使用任何加密库使用密钥和数据计算 RSA。使用正确的键,您将获得输入数据 + 填充。取决于 ruby​​ 程序使用的是公钥还是私钥。希望对您有所帮助。

【讨论】:

因为我更喜欢使用开放标准。我的 Ruby 代码 (pastebin.com/1djhPRxN) 可以在两种方式(加密和解密)中完美运行。我想用我的 C#/.Net 代码获得相同的结果。

以上是关于C#中RSA加密解密的主要内容,如果未能解决你的问题,请参考以下文章

C#中RSA加密解密

RSA 加密 C#

(转)C#实现RSA非对称加密解密

C# BouncyCastle RSA 加密和解密

如何将 Java RSA 公钥移植到 c# 加密功能?

如何在 C# 中使用 RSA 加密文件(大数据)