user1043943
user1043943

Reputation: 23

Converting Byte[] to String to Byte[] - RSA Encryption C#

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));

Upvotes: 2

Views: 10700

Answers (1)

Ioannis Karadimas
Ioannis Karadimas

Reputation: 7906

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.

Upvotes: 9

Related Questions