RSACryptoServiceProvider使用自己的公钥和私钥加密和解密 [英] RSACryptoServiceProvider encrypt and decrypt using own public and private key
本文介绍了RSACryptoServiceProvider使用自己的公钥和私钥加密和解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
static void Main(string [] args)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string pubkey = rsa.ToXmlString(false);
string prikey = rsa.ToXmlString(true);
byte [] someThing = RSAEncrypt(Encoding.Unicode.GetBytes(Hello World),pubkey);
byte [] anotherThing = RSADecrypt(someThing,prikey);
Console.WriteLine(Convert.ToBase64String(anotherThing));
}
加密和解密功能
public static byte [] RSAEncrypt(byte [] plaintext,string destKey)
{
byte [] encryptedData;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(destKey);
encryptedData = rsa.Encrypt(plaintext,true);
rsa.Dispose();
return encryptedData;
}
public static byte [] RSADecrypt(byte [] ciphertext,string srcKey)
{
byte [] decryptptedData;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(srcKey);
decryptptedData = rsa.Decrypt(ciphertext,true);
rsa.Dispose();
return decryptptedData;
}
我期待控制台显示 Hello World
,但它显示这个 SABlAGwAbABvACAAVwBvAHIAbABkAA ==
。我使用RSACryptoServiceProvider错误吗?
解决方案
它是基础64,解码字符串,你会得到Hello world p>
I'm told that for asymmetric cryptography you encrypt plaintext with your public key and decrypt it with your private key. So i've tried the following:
static void Main(string[] args)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string pubkey = rsa.ToXmlString(false);
string prikey = rsa.ToXmlString(true);
byte[] someThing = RSAEncrypt(Encoding.Unicode.GetBytes("Hello World"), pubkey);
byte[] anotherThing = RSADecrypt(someThing, prikey);
Console.WriteLine(Convert.ToBase64String(anotherThing));
}
and the encrypt and decrypt functions
public static byte[] RSAEncrypt(byte[] plaintext, string destKey)
{
byte[] encryptedData;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(destKey);
encryptedData = rsa.Encrypt(plaintext, true);
rsa.Dispose();
return encryptedData;
}
public static byte[] RSADecrypt(byte[] ciphertext, string srcKey)
{
byte[] decryptedData;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(srcKey);
decryptedData = rsa.Decrypt(ciphertext, true);
rsa.Dispose();
return decryptedData;
}
I'm expecting the console to display Hello World
, but it displays this SABlAGwAbABvACAAVwBvAHIAbABkAA==
. Am i using RSACryptoServiceProvider wrongly?
解决方案
It is base 64, decode the string and you will get "Hello world".
这篇关于RSACryptoServiceProvider使用自己的公钥和私钥加密和解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文