志在指尖
用双手敲打未来

RSA加密与解密

1.RSA加密与解密–使用公钥加密、私钥解密
publicclassRSATool
{
publicstringEncrypt(stringstrText,stringstrPublicKey)
{
RSACryptoServiceProviderrsa=newRSACryptoServiceProvider();
rsa.FromXmlString(strPublicKey);
byte[]byteText=Encoding.UTF8.GetBytes(strText);
byte[]byteEntry=rsa.Encrypt(byteText,false);
returnConvert.ToBase64String(byteEntry);
}
publicstringDecrypt(stringstrEntryText,stringstrPrivateKey)
{
RSACryptoServiceProviderrsa=newRSACryptoServiceProvider();
rsa.FromXmlString(strPrivateKey);
byte[]byteEntry=Convert.FromBase64String(strEntryText);
byte[]byteText=rsa.Decrypt(byteEntry,false);
returnEncoding.UTF8.GetString(byteText);
}
publicDictionary<string,string>GetKey()
{
Dictionary<string,string>dictKey=newDictionary<string,string>();
RSACryptoServiceProviderrsa=newRSACryptoServiceProvider();
dictKey.Add(“PublicKey”,rsa.ToXmlString(false));
dictKey.Add(“PrivateKey”,rsa.ToXmlString(true));
returndictKey;
}
}
测试:
ViewCodeC#
2.RSA加密与解密–使用同一个密钥容器进行加密与解密
publicclassRSAToolX
{
publicstringEncrypt(stringstrText)
{
CspParametersCSApars=newCspParameters();
CSApars.KeyContainerName=”Test001″;
RSACryptoServiceProviderrsa=newRSACryptoServiceProvider(CSApars);
byte[]byteText=Encoding.UTF8.GetBytes(strText);
byte[]byteEntry=rsa.Encrypt(byteText,false);
returnConvert.ToBase64String(byteEntry);
}
publicstringDecrypt(stringstrEntryText)
{
CspParametersCSApars=newCspParameters();
CSApars.KeyContainerName=”Test001″;
RSACryptoServiceProviderrsa=newRSACryptoServiceProvider(CSApars);
byte[]byteEntry=Convert.FromBase64String(strEntryText);
byte[]byteText=rsa.Decrypt(byteEntry,false);
returnEncoding.UTF8.GetString(byteText);
}
}

未经允许不得转载:IT技术网站 » RSA加密与解密
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载