N
N
Nikita Kochetkov2016-01-14 23:19:43
C++ / C#
Nikita Kochetkov, 2016-01-14 23:19:43

An object reference does not point to an instance of an object. What should I do?

The error is on the line

byte[] bytesDecrypted = csp.Decrypt(encData, false);

The code:
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.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

namespace WindowsFormsApplication7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = openFileDialog1.FileName;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            X509Certificate2 x509 = new X509Certificate2(X509Certificate2.CreateFromCertFile(@textBox1.Text));
            using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider)x509.PublicKey.Key)
            {
                byte[] data = Encoding.UTF8.GetBytes(richTextBox1.Text);
                byte[] encData = csp.Encrypt(data, false);
                richTextBox2.Text = Convert.ToBase64String(encData);
               
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
             X509Certificate2 x509 = new X509Certificate2(X509Certificate2.CreateFromCertFile(@textBox2.Text));
             byte[] encData = Convert.FromBase64String(richTextBox2.Text);
             
             using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider)x509.PrivateKey)
             {
                 byte[] bytesDecrypted = csp.Decrypt(encData, false);
                 int len = bytesDecrypted.Length;
                 char[] val = new char[len];
                 val = Encoding.Unicode.GetChars(bytesDecrypted);
                 richTextBox3.Text = string.Join("", val);
                 //richTextBox3.Text = Encoding.UTF8.GetString(bytesDecrypted);
             }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (openFileDialog2.ShowDialog() == DialogResult.OK)
            {
                textBox2.Text = openFileDialog2.FileName;
            }
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Kochetkov, 2016-01-14
@fiercekilla

Alexey Nemiro :
Found null here:
I have a PrivateKey, but I don’t understand why null is there, I
use a pfx certificate for encryption, cer for decryption

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question