Monday, August 30, 2010

Sha1 encoder using .NET

public enum EncodeStyle


{

Dig,

Hex,

Base64

};



static string ByteArrayToString(byte[] arrInput, EncodeStyle encode)

{

int i;

StringBuilder sOutput = new StringBuilder(arrInput.Length);

if(EncodeStyle.Base64 == encode)

{

return Convert.ToBase64String(arrInput);

}



for (i = 0; i < arrInput.Length; i++)

{

switch(encode)

{

case EncodeStyle.Dig:

//encode to decimal with 3 digits so 7 will be 007 (as range of 8 bit is 127 to -128)

sOutput.Append(arrInput[i].ToString("D3"));

break;

case EncodeStyle.Hex:

sOutput.Append(arrInput[i].ToString("X2"));

break;

}



}

return sOutput.ToString();

}



static string SHA1HashEncode(string filePath, EncodeStyle encode)

{

//implementing sha1 decimal encoding : SHA1.exe -encode=dig

SHA1 a = new SHA1CryptoServiceProvider();

byte[] arr = new byte[60];

string hash = "";

using (StreamReader sr = new StreamReader(filePath))

{

arr = a.ComputeHash(sr.BaseStream);

hash = ByteArrayToString(arr, encode);

}

return hash;

}



static void Main(string[] args)

{

string test = SHA1HashEncode(@"c:\abc.xml", EncodeStyle.Base64);

No comments:

Post a Comment