I'm trying to build Bob and Alice asymmetric encryption and decryption implementation using RSACryptoServiceProvider
for that I have
- console app Bob (can consider as the sender)
- console app Alice (can consider as the receiver)
console app Bob can encrypt using its public key and then console app Alice can decrypt this using its private key
so this is Bob Console app
class Program
{
static void Main(string[] args)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string publicKey = rsa.ToXmlString(false);
string privateKey = rsa.ToXmlString(true);
EncryptText(publicKey, "Hello from C# Corner", "encryptedData.dat");
}
public static void EncryptText(string publicKey, string text, string fileName)
{
UnicodeEncoding byteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = byteConverter.GetBytes(text);
byte[] encryptedData;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(publicKey);
encryptedData = rsa.Encrypt(dataToEncrypt, false);
}
File.WriteAllBytes(fileName, encryptedData);
Console.WriteLine("Data has been encrypted");
}
}
this is Alice Console app
class Program
{
static void Main(string[] args)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string publicKey = rsa.ToXmlString(false);
string privateKey = rsa.ToXmlString(true);
Console.WriteLine("Decrypted message: {0}", DecryptData(privateKey, "encryptedData.dat"));
}
public static string DecryptData(string privateKey, string fileName)
{
byte[] dataToDecrypt = File.ReadAllBytes(fileName);
byte[] decryptedData;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(privateKey);
decryptedData = rsa.Decrypt(dataToDecrypt, false);
}
UnicodeEncoding byteConverter = new UnicodeEncoding();
return byteConverter.GetString(decryptedData);
}
}
when It's decrypting I'm getting the error as
System.Security.Cryptography.CryptographicException: 'The parameter is incorrect.
could you please advise on this :)