RSA非对称可逆加密

Posted anyihen

tags:

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

/// <summary>
/// RSA ECC
/// 可逆非对称加密
/// 非对称加密算法的优点是密钥管理很方便,缺点是速度慢。
/// </summary>
using System.Security.Cryptography;
public class RsaEncrypt
{

/// <summary>
/// publicKey,privateKey
/// </summary>
/// <returns></returns>
public static KeyValuePair<string, string> GetKeyPair()
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
string publicKey = RSA.ToXmlString(false);
string privateKey = RSA.ToXmlString(true);
return new KeyValuePair<string, string>(publicKey, privateKey);
}

/// <summary>
/// 加密:内容+公钥
/// </summary>
/// <param name="content"></param>
/// <param name="publicKey"></param>
/// <returns></returns>
public static string Encrypt(string content, string publicKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(publicKey);
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] DataToEncrypt = ByteConverter.GetBytes(content);
byte[] resultBytes = rsa.Encrypt(DataToEncrypt, false);
return Convert.ToBase64String(resultBytes);
}

/// <summary>
/// 加密
/// </summary>
/// <param name="content"></param>
/// <param name="publicKey">返还公钥</param>
/// <param name="privateKey">返回密钥</param>
/// <returns>加密后结果</returns>
public static string Encrypt(string content, out string publicKey, out string privateKey)
{
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
publicKey = rsaProvider.ToXmlString(false);
privateKey = rsaProvider.ToXmlString(true);

UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] DataToEncrypt = ByteConverter.GetBytes(content);
byte[] resultBytes = rsaProvider.Encrypt(DataToEncrypt, false);
return Convert.ToBase64String(resultBytes);
}

/// <summary>
/// 解密 内容+私钥
/// </summary>
/// <param name="content"></param>
/// <param name="privateKey"></param>
/// <returns></returns>
public static string Decrypt(string content, string privateKey)
{
byte[] dataToDecrypt = Convert.FromBase64String(content);
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.FromXmlString(privateKey);
byte[] resultBytes = RSA.Decrypt(dataToDecrypt, false);
UnicodeEncoding ByteConverter = new UnicodeEncoding();
return ByteConverter.GetString(resultBytes);
}
}


//非对称加密
string publicKey = "";
string privateKey = "";
string rsaEn = RsaEncrypt.Encrypt("netnetnetnetnetnetnetne", out publicKey, out privateKey);
string rsaDe = RsaEncrypt.Decrypt(rsaEn, privateKey);

KeyValuePair<string, string> publicPrivate = RsaEncrypt.GetKeyPair();
string rsaEn1 = RsaEncrypt.Encrypt("net", publicPrivate.Key);
string rsaDe1 = RsaEncrypt.Decrypt(rsaEn1, publicPrivate.Value);
//加密key 解密key
//公开加密key,接受加密消息,因为只有我一个人能解密
//公开解密key,用于签名,表明数据一定是我发的,因为只有我有加密的key
//公钥私钥只是跟公开与否有关

以上是关于RSA非对称可逆加密的主要内容,如果未能解决你的问题,请参考以下文章

基于C#的RSA非对称加密算法

技术 | RSA非对称加密算法详解

移动端加解密

码农吐糟面试官:居然问我md5是对称加密还是非对称,故意的吧?

RSA  加密算法(原理篇)

非对称加密及RSA加密算法