Ask coding questions

← Back to all posts
Hashing password
Bunnytoes (165)

I found some code online to hash passwords and I have an annoying error I need to fix, it says an object reference is required but when I do it it comes but with an error still. The entire code is

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Security.Cryptography;

class MainClass {
  public string ComputeHash(byte[] bytesToHash, byte[] salt)
    var byteResult = new Rfc2898DeriveBytes(bytesToHash, salt, 10000);
    return Convert.ToBase64String(byteResult.GetBytes(24));
public static string GenerateSalt()
    var bytes = new byte[128 / 8];
    var rng = new RNGCryptoServiceProvider();
    return Convert.ToBase64String(bytes);
  public static void Main (string[] args) {
    Console.WriteLine("Would you like to sign up or login?");
    string hmm = Console.ReadLine().ToUpper();
    if (hmm == "SIGN UP")
    Console.WriteLine("Enter username");
    string username = Console.ReadLine();
Console.WriteLine("Enter password");
string password = Console.ReadLine();

var newSalt = GenerateSalt();
var hashedPassword = ComputeHash(Encoding.UTF8.GetBytes(password1), Encoding.UTF8.GetBytes(newSalt));
    using (TextWriter w = File.CreateText("storeInfo.txt"))
    if (hmm == "LOGIN")
    Console.WriteLine("Coming soon");

please help

Answered by Kai_Justice (271) [earned 5 cycles]
View Answer
Kai_Justice (271)

Change line 16 to: public static string ComputeHash(byte[] bytesToHash, byte[] salt).
Since main is a static function and does not have a reference to the MainClass object you'll have to make any functions you want to use in it static so they can be referenced without creating an object. I don't use C# so this is just what I picked up from using other object oriented languages.

Bunnytoes (165)

@Kai_Justice thanks so much! it works. Would you be able to help with login, I am thinking of having the user enter their username and password and hashing and salting the password to see if it's there, but I need to group the data