使用RSA在C#中使用正确的私钥和公钥对进行解密时出现错误数据异常

Taf*_*rwa 1 c# rsa rsacryptoserviceprovider

这是我的解密过程代码:

    private RSACryptoServiceProvider _rsa;
    private string _privateKey;
    private string _publicKey;

    public RsaLibrary()
    {
        //initialsing the RSA object taking the option of a 1024 key size
        _rsa = new RSACryptoServiceProvider(1024);
        _privateKey = _rsa.ToXmlString(true);
        _publicKey = _rsa.ToXmlString(false);

    }

 public string Decrypt(string ciphertext, string privateKey_ = null)
    {
        if (String.IsNullOrEmpty(privateKey_))
        {
            return DecryptToBytes(ciphertext, _privateKey);
        }
        else
        {
            return DecryptToBytes(ciphertext, privateKey_);
        }
    }

    private string DecryptToBytes(string ciphertext, string privateKey)
    {
        if (String.IsNullOrEmpty(privateKey))
        {
            throw new ArgumentNullException("Error: No key provided.");
        }
        if (ciphertext.Length<=0)
        {
            throw new ArgumentNullException("Error: No message to decrypt.");
        }

        byte[] plaintext;
        byte[] ciphertext_Bytes = Encoding.Unicode.GetBytes(ciphertext);
        _rsa.FromXmlString(privateKey);

        plaintext = _rsa.Decrypt(ciphertext_Bytes, false);

        return Encoding.Unicode.GetString(plaintext);
    }
Run Code Online (Sandbox Code Playgroud)

加密代码:

        private string EncryptToByte(string plaintext, string publicKey)
    {
        if (String.IsNullOrEmpty(publicKey))
        {
            throw new ArgumentNullException("Error: No key provided.");
        }
        if (plaintext.Length<=0)
        {
            throw new ArgumentNullException("Error: No message to incrypt");
        }


        byte[] ciphertext;
        byte[] plaintext_Bytes = Encoding.Unicode.GetBytes(plaintext);
        _rsa.FromXmlString(publicKey);

        ciphertext = _rsa.Encrypt(plaintext_Bytes, false);
        return Convert.ToBase64String(ciphertext);
    }
Run Code Online (Sandbox Code Playgroud)

我看不出哪里出错了.我确保钥匙是正确的.我在构造函数中使用此行提取的公共一个:_publicKey = _rsa.ToXmlString(false); 此公钥显示在我创建的表单上.私人我使用"真"而不是假.

有任何想法吗?

Jon*_*eet 5

密文不太可能是真正的UTF-16编码文本.假设加密方有类似的东西:

string encryptedText = Encoding.Unicode.GetString(encryptedBytes);
Run Code Online (Sandbox Code Playgroud)

你基本上丢失了数据.加密的结果不是文本 - 它是任意二进制数据.如果由于某些传输原因要将其转换为文本,则应使用Base64,例如

string base64EncryptedText = Convert.ToBase64String(encryptedBytes);
Run Code Online (Sandbox Code Playgroud)

然后用于Convert.FromBase64String恢复准备解密的原始加密二进制数据.