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));
2
  • 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). Commented Nov 21, 2011 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 Commented Nov 21, 2011 at 13:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

just one more question, if I was to show this content in a textbox i would have to show the "encodedString", would I?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.