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

本文关键字:RSA 加密 到字节 字节 转换 字符串 | 更新日期: 2023-09-27 18:15:14

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

我尝试过ascii编码,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));

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

下面的代码演示了您需要的内容。

    [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编码和解码。