I was working on a project. Encryption is working fine but when it comes to decryption my program is throwing "Bad data Exception". How do I remedy this problem?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
byte[] cipher;
byte[] plain;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private static string Encrypt(byte[] plain)
{
byte[] encrypted;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
StreamReader StRe = new StreamReader("D:\PjesaVetemPublike.xml");
string VetemPublikeXML = StRe.ReadToEnd();
rsa.FromXmlString(VetemPublikeXML);
StRe.Close();
encrypted = rsa.Encrypt(plain, true);
return Encoding.UTF8.GetString(encrypted);
}
private static string Decrypt(byte[] encrypted)
{
byte[] decrypted;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
StreamReader StRe = new
StreamReader("D:\PjesaPublikeDhePrivate.xml");
string PublikeDhePrivate = StRe.ReadToEnd();
rsa.FromXmlString(PublikeDhePrivate);
StRe.Close();
decrypted = rsa.Decrypt(encrypted, false); //THE ERROR APPEARS RIGHT HERE
return Encoding.UTF8.GetString(decrypted);
}
private void button1_Click(object sender, EventArgs e)
{
plain = Encoding.UTF8.GetBytes(txtPlain.Text);
txtCipher.Text = Encrypt(plain);
}
private void button2_Click(object sender, EventArgs e)
{
txtDekriptuar.Text = Decrypt(cipher);
}
}
}
See Question&Answers more detail:os