2

If I give the decrypter RSAalg2.Decrypt(encryptedData, false); it works fine but I need to convert the encrypted data (byte array) to a string then back to a byte array.

I've tried ASCIIEncoding, UTF-8 rather than Unicode with no luck. I'd appreciate any help I can get. Thanks

UnicodeEncoding ByteConverter = new UnicodeEncoding();

string dataString = "Test";

byte[] dataToEncrypt = ByteConverter.GetBytes(dataString);
byte[] encryptedData;
byte[] decryptedData;

RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

Console.WriteLine("Original Data: {0}", dataString);

encryptedData = RSAalg.Encrypt(dataToEncrypt, false);

Console.WriteLine("Encrypted Data: {0}", ByteConverter.GetString(encryptedData));

String XML = RSAalg.ToXmlString(true);
XmlDocument doc = new XmlDocument();
doc.LoadXml(XML);
doc.Save(Environment.CurrentDirectory + "\\key.xml");

RSACryptoServiceProvider RSAalg2 = new RSACryptoServiceProvider();

StreamReader sr2 = File.OpenText(Environment.CurrentDirectory + "\\key.xml");
string rsaXml2 = sr2.ReadToEnd();
sr2.Close();

RSAalg2.FromXmlString(rsaXml2);
string s = ByteConverter.GetString(encryptedData);
byte[] se = ByteConverter.GetBytes(s);
decryptedData = RSAalg2.Decrypt(se, false);

Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData));
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
user1043943
  • 23
  • 1
  • 1
  • 4
  • Your question is actually not at all about RSA. The way you use the UnicodeEncoding class is correct so the problem probably is in the other parts (encryption). – foowtf Nov 21 '11 at 13:34
  • 1
    'with no luck' isnt very descriptive. perhaps explain where it fails, any exceptions you get and so on. Does it need to be written to a `String`? If yes, why? If no, simply write the `byte[]` to disk using `System.IO.File.WriteAllBytes` – wal Nov 21 '11 at 13:39

1 Answers1

9

The code below demonstrates what you are after.

    [Test]
    public void RsaEncryptDecryptDemo()
    {
        const string str = "Test";
        var rsa = new RSACryptoServiceProvider();
        var encodedData = rsa.Encrypt(Encoding.UTF8.GetBytes(str), false);

        var encodedString = Convert.ToBase64String(encodedData);
        var decodedData = rsa.Decrypt(Convert.FromBase64String(encodedString), false);
        var decodedStr = Encoding.UTF8.GetString(decodedData);

        Assert.AreEqual(str, decodedStr);
    }

The trick is to convert your byte array into a form that can be represented as a string. To that effect, the example above utilizes Base64 encoding and decoding.

Ioannis Karadimas
  • 7,746
  • 3
  • 35
  • 45
  • just one more question, if I was to show this content in a textbox i would have to show the "encodedString", would I? – user1043943 Nov 21 '11 at 19:15