Thursday, February 7, 2013

C# SHA256 Hash test from ansi & utf-8 bytes

C# SHA256 Hash test from ansi & utf-8 bytes

using System;
using System.Text;
using System.Security.Cryptography;
 
namespace HashTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string unicodeString = "미잘";
            string salt = "말";
             
            byte[] ansi = Encoding.Default.GetBytes(unicodeString);
            byte[] utf8 = Encoding.Convert(Encoding.Default, Encoding.UTF8, ansi);           
           
            HMACSHA256 sha256 = new HMACSHA256();
                         
            byte[] hashAnsi, hashUtf8;
 
            sha256.Key = Encoding.Default.GetBytes(salt);
            hashAnsi = sha256.ComputeHash(ansi);
 
            sha256.Key = Encoding.UTF8.GetBytes(salt);
            hashUtf8 = sha256.ComputeHash(utf8);
 
            Console.Write("BYTE-A: ");
            PrintByteArray(ansi);
            Console.Write("BYTE-U: ");
            PrintByteArray(utf8);
            Console.Write("HASH-A: ");
            PrintByteArray(hashAnsi);
            Console.Write("HASH-U: ");
            PrintByteArray(hashUtf8);
            Console.ReadLine();
        }
 
        private static void PrintByteArray(byte[] array)
        {
            int i;
            for (i = 0; i < array.Length; i++)
            {
                Console.Write(String.Format("{0:X2}", array[i]));
                if ((i % 4) == 3) Console.Write(" ");
            }
            Console.WriteLine();
        }
    }
}
BYTE-A: B9CCC0DF
BYTE-U: EBAFB8EC 9E98
HASH-A: 6C966F48 76AE7D76 FFD59579 5B74F45F D7DC659D 22812D04 7FF7CB32 7666E41C
HASH-U: BA2C88BC 6C1A976C 70BFF480 7EB367A7 9F0EE00E 50FAC487 D71718C2 5DE09CAC