Adesanya Olusegun

Adesanya Olusegun

  • NA
  • 19
  • 26.7k

input string does not contain a valid encoding of the 'RSA'

May 26 2014 9:18 AM
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Security.Cryptography;

namespace CryptographicClasses
{
class BigEncryption
{
public static void PubToXml()
{
var txt = string.Empty;
using (var stream = File.OpenText("public_key.txt"))
{
txt = stream.ReadToEnd();
}

var xml = new XDocument(new XElement("Data", new XElement("info", txt)));
xml.Save(Path.ChangeExtension("public_key.txt", ".xml"));
}

public static void PriToXml()
{
var txt = string.Empty;
using (var stream = File.OpenText("private_key.txt"))
{
txt = stream.ReadToEnd();
}

var xml = new XDocument(new XElement("Data", new XElement("info", txt)));
xml.Save(Path.ChangeExtension("private_key.txt", ".xml"));
}

public static string Encrypt()
{
try
{
PubToXml();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
StreamReader readme = File.OpenText("public_key.xml");
string rsaXml = readme.ReadToEnd();
readme.Close();
rsa.FromXmlString(rsaXml);
Console.WriteLine("Enter text here");
string message = Console.ReadLine();

byte[] encrypted = rsa.Encrypt(System.Text.ASCIIEncoding.ASCII.GetBytes(message), false);

FileStream steam = new FileStream("Lmessage.dat", FileMode.Create);
steam.Write(encrypted, 0, encrypted.Length);
steam.Close();

}

catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

return "0";
}

public static string Decrypt()
{
PriToXml();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
StreamReader readme = File.OpenText("private_key.xml");
string rsaXml = readme.ReadToEnd();
readme.Close();
rsa.FromXmlString(rsaXml);
string message = Console.ReadLine();

byte[] decrypted = rsa.Decrypt(System.Text.ASCIIEncoding.ASCII.GetBytes(message), false);

FileStream steam = new FileStream("Lmessage.dat", FileMode.Create);
steam.Write(decrypted, 0, decrypted.Length);
steam.Close();
return "0";
}
}
}