Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

c# - Bad Data exception during RSA decryption

I was working on a project. Encryption is working fine but when it comes to decryption my program is throwing "Bad data Exception". How do I remedy this problem?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace WindowsFormsApplication2
{

    public partial class Form1 : Form
    {
        byte[] cipher;
        byte[] plain;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }


        private static string Encrypt(byte[] plain)
        {
            byte[] encrypted;
          RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                StreamReader StRe = new StreamReader("D:\PjesaVetemPublike.xml");
                string VetemPublikeXML = StRe.ReadToEnd();
                rsa.FromXmlString(VetemPublikeXML);
                StRe.Close();
                encrypted = rsa.Encrypt(plain, true);

            return Encoding.UTF8.GetString(encrypted);
        }

        private static string Decrypt(byte[] encrypted)
        {
            byte[] decrypted;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                StreamReader StRe = new         
         StreamReader("D:\PjesaPublikeDhePrivate.xml");
                string PublikeDhePrivate = StRe.ReadToEnd();
                rsa.FromXmlString(PublikeDhePrivate);
                StRe.Close();

                decrypted = rsa.Decrypt(encrypted, false);   //THE ERROR APPEARS RIGHT HERE

            return Encoding.UTF8.GetString(decrypted);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            plain = Encoding.UTF8.GetBytes(txtPlain.Text);
            txtCipher.Text = Encrypt(plain);

        }

        private void button2_Click(object sender, EventArgs e)
        {

            txtDekriptuar.Text = Decrypt(cipher);
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Among other problems you are assuming that the ciphertext can be converted to UTF-8 meaningfully, and that isn't guaranteed.

If you want to encrypt text and transmit/store the encrypted contents as text you need to follow this pattern:

Encrypt(textIn => textOut):

  • Convert textIn to bytesIn via some encoding. UTF-8 is pretty good.
  • Encrypt bytesIn to bytesOut.
  • Apply a lossless encoding to bytesOut. Base64 is almost always the best choice for this, and is the best one that's built in to .NET. (textOut = Convert.ToBase64String(bytesOut)).
  • Return textOut.

Decrypt(textIn => textOut):

  • Apply the inverse transform from Encrypt to turn textIn to bytesIn. So likely Convert.FromBase64String.
  • Decrypt bytesIn to bytesOut.
  • Apply a text encoding transform to turn bytesOut to textOut. There's nothing that really says that this needs to be the same as the one used in Encrypt, but it probably makes sense to do so.

The problem with using UTF-8 (or ASCII or UCS-2, etc) for a textual representation of encrypted data is that the encrypted data can legitimately contain a byte whose value is 0x00 (or a control code, linebreak, etc). While .NET, for the most part, happily transports embedded null characters in a string it definitely can be a large source of confusion (and not all languages/functions handle it the same).

Other fun characters:

  • What does your language/function do for an embedded 0x7F (Delete)?
  • If you store the string in a single-line text field, what happens to any CR or LF characters? What does your program do on Windows if it gets CR without LF, or LF without CR?
  • A Unix command-line with 0x13 (^S) may appear to hang, but it's just waiting on 0x11 (^Q).

What encodings to use for storing ciphertext? Well, anything that safely packs control characters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...