#c# #winforms
#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 amp;amp; (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)) ||
(cmbType.SelectedIndex == 1 amp;amp; (txtURL.Text == string.Empty || txtPassword.Text == string.Empty)) ||
(cmbType.SelectedIndex == 2 amp;amp; (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);
}
}
}
С уважением.
Ответ №1:
Вы должны установить для вашего 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;
}
Ответ №2:
mainWindow
устанавливается только в этом конструкторе: public AddEntryWindow(MainWindow viaParameter)
, не в том случае, если вы используете этот: public AddEntryWindow(string user, string pass)
или конструктор по умолчанию.
Вы всегда можете поставить точку останова в строке, которая вызывает исключение, и проверить каждую переменную.
Комментарии:
1. Я думаю, вы правы. Возможно, я забыл какой-то код в файле MainWindow.cs. Необходимо перепроверить