将字节[]转换为字符串转换为字节[] - RSA加密C#

时间:2011-11-21 13:24:23

标签: c# encryption base64 rsa

如果我给解密器RSAalg2.Decrypt(encryptedData, false);它工作正常但我需要将加密数据(字节数组)转换为字符串然后再转换回字节数组。

我尝试过ASCIIEncoding,UTF-8而不是Unicode而没有运气。我很感激我能得到任何帮助。感谢

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

1 个答案:

答案 0 :(得分:5)

下面的代码演示了您的目标。

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

诀窍是将您的字节数组转换为可以表示为字符串的形式。为此,上面的示例使用Base64编码和解码。