特定代码行后出现错误

时间:2011-11-04 08:47:17

标签: c# winforms

我收到错误说:Object reference not set to an instance of an object.我不希望这是导致问题的实际行,但它出现了:

mainWindow.ChangeTextBox = stringBuilder.ToString();

似乎它在第一行代码之后导致错误:

        string encrypted = en.Encrypt(stringBuilder.ToString(), user, pass);
        string decrypted = en.Decrypt(encrypted, user, pass);

可能是什么原因?

AddEntryWindow.cs

using System;
using System.Windows.Forms;
// Needed to be used with StringBuilder
using System.Text;
// Needed to be used with ArrayList.
using System.Collections;

namespace Store_Passwords_and_Serial_Codes
{
    public partial class AddEntryWindow : Form
    {
        string user, pass;
        // Initializind ArrayList to store all data needed to be added or retrived.
        private ArrayList addedEntry = new ArrayList();

        // Initializing MainWindow form.
        MainWindow mainWindow;

        // Making authentication possible.
        // AuthenticateUser authenticateUser = new AuthenticateUser();

        EncryptDecrypt en = new EncryptDecrypt();

        // Default constructor to initialize the form.
        public AddEntryWindow()
        {
            InitializeComponent();
        }

        public AddEntryWindow(string user, string pass)
            : this() // important!
        {
            this.user = user;
            this.pass = pass;
        }


        public AddEntryWindow(MainWindow viaParameter) : this()
        {
            mainWindow = viaParameter;
        }

        private void AddEntryWindow_Load(object sender, EventArgs e)
        { }

        private void btnAddEntry_Click(object sender, EventArgs e)
        {
            // Making sure that type is selected.
            if (cmbType.SelectedIndex == -1)
            {
                MessageBox.Show("Please select entry type!", "Error!", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            // Each field must be filled for specified type.
            // Here we are checking if all fields were filled.
            else if ((cmbType.SelectedIndex == 0 && (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)) ||
                (cmbType.SelectedIndex == 1 && (txtURL.Text == string.Empty || txtPassword.Text == string.Empty)) ||
                (cmbType.SelectedIndex == 2 && (txtSoftwareName.Text == string.Empty || txtSerialCode.Text == string.Empty)))
            {
                MessageBox.Show("Please fill all the fields!", "Error!", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                int totalEntries = 0;

                if(cmbType.SelectedIndex == 0)
                    addedEntry.Add(new AddPC(cmbType.Text, 
                        txtUserName.Text, txtPassword.Text));

                else if(cmbType.SelectedIndex == 1)
                    addedEntry.Add(new AddWebSite(cmbType.Text, 
                        txtUserName.Text, txtPassword.Text, txtURL.Text));

                else if(cmbType.SelectedIndex == 2)
                    addedEntry.Add(new AddSerialCode(cmbType.Text, 
                        txtSoftwareName.Text, txtSerialCode.Text));

                StringBuilder stringBuilder = new StringBuilder();

                foreach (var list in addedEntry)
                {
                    if (list is AddPC)
                    {
                        totalEntries++;
                        AddPC tmp = (AddPC)list;
                        stringBuilder.Append(tmp.ToString());
                    }
                    else if (list is AddWebSite)
                    {
                        totalEntries++;
                        AddWebSite tmp = (AddWebSite)list;
                        stringBuilder.Append(tmp.ToString());
                    }
                    else if (list is AddSerialCode)
                    {
                        totalEntries++;
                        AddSerialCode tmp = (AddSerialCode)list;
                        stringBuilder.Append(tmp.ToString());
                    }
                }

                MessageBox.Show(user + pass);

                string encrypted = en.Encrypt(stringBuilder.ToString(), user, pass);
                string decrypted = en.Decrypt(encrypted, user, pass);


                    //+ Environment.NewLine +
                    //encrypted + Environment.NewLine + decrypted);

                mainWindow.ChangeTextBox = stringBuilder.ToString();

                //mainWindow.tsslStatus.Text = "A total of " + totalEntries + " entries added.";

                // Clearing all fields.
                //ClearFields();
            }
        }

        private void btnClear_Click(object sender, EventArgs e){}
        private void btnClose_Click(object sender, EventArgs e){}
        private void cmbType_SelectedIndexChanged(object sender, EventArgs e){}
    }
}

EncryptDecrypt.cs

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace Store_Passwords_and_Serial_Codes
{
    class EncryptDecrypt
    {
        string input, userName, password;

        RijndaelManaged Crypto = new RijndaelManaged();

        public EncryptDecrypt()
        {
        }

        public EncryptDecrypt(string input, string userName, string password)
        {
            this.input = input;
            this.userName = userName;
            this.password = password;
        }

        public string Encrypt(string PlainText, string pass, string usrName)
        {
            string HashAlgorithm = "SHA1"; 
            int PasswordIterations = 2;
            string InitialVector = "OFRna73m*aze01xY";
            int KeySize = 256;

            this.input = PlainText;

            if (string.IsNullOrEmpty(PlainText))
                return "";

            byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
            byte[] SaltValueBytes = Encoding.ASCII.GetBytes(usrName);
            byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);

            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(pass, SaltValueBytes, HashAlgorithm, PasswordIterations);

            byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);

            RijndaelManaged SymmetricKey = new RijndaelManaged();

            SymmetricKey.Mode = CipherMode.CBC;

            byte[] CipherTextBytes = null;

            using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
            {
                using (MemoryStream MemStream = new MemoryStream())
                {
                    using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                    {
                        CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                        CryptoStream.FlushFinalBlock();
                        CipherTextBytes = MemStream.ToArray();
                        MemStream.Close();
                        CryptoStream.Close();
                    }
                }
            }

            SymmetricKey.Clear();
            return Convert.ToBase64String(CipherTextBytes);
        }

        public string Decrypt(string CipherText, string pass, string usrName)
        {
            string HashAlgorithm = "SHA1"; 
            int PasswordIterations = 2;
            string InitialVector = "OFRna73m*aze01xY";
            int KeySize = 256;

             if (string.IsNullOrEmpty(CipherText))
                 return "";

             byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);

             byte[] SaltValueBytes = Encoding.ASCII.GetBytes(usrName);
             byte[] CipherTextBytes = Convert.FromBase64String(CipherText);

             PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(pass, SaltValueBytes, HashAlgorithm, PasswordIterations);

             byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);

             RijndaelManaged SymmetricKey = new RijndaelManaged();

             SymmetricKey.Mode = CipherMode.CBC;

             byte[] PlainTextBytes = new byte[CipherTextBytes.Length];

             int ByteCount = 0;

             using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
             {
                 using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                 {

                     using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                     {
                         ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                         MemStream.Close();
                         CryptoStream.Close();
                     }
                 }
             }

             SymmetricKey.Clear();
             return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
         }
    }
}

问候。

2 个答案:

答案 0 :(得分:5)

您应该将mainWindow设置为MainWindow的实例。

在以下构造函数中,您没有这样做。

    public AddEntryWindow(string user, string pass)
        : this() 
    {
        this.user = user;
        this.pass = pass;
    }


    public AddEntryWindow(MainWindow viaParameter, string user, string pass)
        : this() 
    {

        mainWindow = viaParameter;
        this.user = user;
        this.pass = pass;
    }

答案 1 :(得分:2)

mainWindow仅在此构造函数中设置:public AddEntryWindow(MainWindow viaParameter),如果您使用此public AddEntryWindow(string user, string pass)或默认构造函数,则不会。

您总是可以在引发异常的行上放置一个断点,并检查每个变量。