tags:

views:

84

answers:

3

Note: I will not be using salts. Thanks for your advice though!

I'm testing how to hash a password using SHA1 and can't seem to wrap my head around it. My database column is Password char(40) not null.

Here's my code:

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

namespace Consumer
{
    class Program
    {
        static void Main(string[] args)
        {
            string password = "Mypassword";
            byte[] data password.tobytearray()???
            byte[] result;

            SHA1 sha = new SHA1CryptoServiceProvider();
            // This is one implementation of the abstract class SHA1.
            result = sha.ComputeHash(data);
            Console.WriteLine(result.ToString());
            Console.ReadLine();

        }
    }
}
+2  A: 

To convert a string to a Byte[], use the Encoding class.

Also, result is a Byte[], which doesn't override ToString().

To get a string representation of the byte array, you can call BitConverter.ToString or Convert.ToBase64String.
In a database, you should store the raw byte array directly.

SLaks
+3  A: 

It sounds like you're trying to convert a string into a byte[]. This is done by using one of the Encoding classes.

byte[] data = System.Text.Encoding.Unicode.GetBytes(password);
byte[] data = System.Text.Encoding.ASCII.GetBytes(password);

I'm not sure which is most appropriate for your scenario but I would use Unicode unless I had a specific reason to do otherwise.

JaredPar
A: 

So your correct program would be something like

    static void Main(string[] args)
    {
        string password = "Mypassword";
        byte[] data = System.Text.Encoding.ASCII.GetBytes(password);
        //or byte[] data = System.Text.Encoding.Unicode.GetBytes(password);
        byte[] result;

        SHA1 sha = new SHA1CryptoServiceProvider();
        // This is one implementation of the abstract class SHA1.
        result = sha.ComputeHash(data);
        Console.WriteLine(Convert.ToBase64String(result));
        Console.ReadLine();
    }
Aj M