The SQL Server and .Net equivalent of PHP and MySQL's SHA1 function

In PHP and MySql there is an sha1(str) function which generates an sha1 hash of a string.

Their usages are simple:
<?php
   echo sha1('password');
?>
//Outputs:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
mysql> select sha1('password');
+------------------------------------------+
| sha1('password')                         |
+------------------------------------------+
| 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8 |
+------------------------------------------+
1 row in set (0.00 sec)
Similarly, .Net has an SHA1 method within the System.Security.Cryptography  namespace which can be used in the following manner to generate the same hash.
 public static string Sha1(string hashStr, Encoding encoding)
{            
   var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
   var hash = sha1.ComputeHash(encoding.GetBytes(hashStr));
   return BitConverter.ToString(hash).Replace("-", "");            
}


Console.WriteLine(Sha1("password", Encoding.ASCII)); -> 
//Outputs:5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8
In SQL Server there is a HashBytes function which can return the sha1 hash as well. Since the HashBytes function returns a varbinary, the result can be converted to a string using a sql server system function in order to match the php or mysql function.
select sys.fn_varbintohexsubstring(0, HashBytes('SHA1', 'password'),1,0)
--------------------------------------------------------------------------
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8

(1 row(s) affected)

Comments

Popular posts from this blog

AutoItX4Java - Java AutoIt Bridge

Automated web testing with Java, Selenium RC, LoggingSelenium, HtmlUnit and TestNG