算法简介
链接如下:
https://blog.csdn.net/f_957995490/article/details/108413226
代码示例
使用的是RSA算法:
//获取密钥和公钥
public void RSAKey(out string xmlKeys, out string xmlPublicKey)
{
try
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
xmlKeys = rsa.ToXmlString(true);
xmlPublicKey = rsa.ToXmlString(false);
}
catch (Exception ex)
{
throw ex;
}
}
//RSA的加密函数
public string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)
{
try
{
byte[] PlainTextBArray;
byte[] CypherTextBArray;
string Result;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPublicKey);
PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString);
CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
Result = Convert.ToBase64String(CypherTextBArray);
return Result;
}
catch (Exception ex)
{
throw ex;
}
}
//RSA的加密函数
public string RSAEncrypt(string xmlPublicKey, byte[] EncryptString)
{
try
{
byte[] CypherTextBArray;
string Result;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPublicKey);
CypherTextBArray = rsa.Encrypt(EncryptString, false);
Result = Convert.ToBase64String(CypherTextBArray);
return Result;
}
catch (Exception ex)
{
throw ex;
}
}
//RSA的解密函数
public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)
{
try
{
byte[] PlainTextBArray;
byte[] DypherTextBArray;
string Result;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivateKey);
PlainTextBArray = Convert.FromBase64String(m_strDecryptString);
//XP版本以上为true
DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);
Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
return Result;
}
catch (Exception ex)
{
throw ex;
}
}
//RSA的解密函数
public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString)
{
try
{
byte[] DypherTextBArray;
string Result;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivateKey);
DypherTextBArray = rsa.Decrypt(DecryptString, false);
Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
return Result;
}
catch (Exception ex)
{
throw ex;
}
}