title: Calculating SHA1 hash of a 'nvarchar' string using T-SQL
body: <p>I'm trying to calculate <code>SHA1</code> hash of a unicode string using T-SQL. The below code works fine with <code>ASCII</code> strings:</p>
  
  <pre><code>declare @input varchar(50)
  set @input = 'some text'
  print 'SHA1 Hash: ' + UPPER(master.dbo.fn_varbintohexsubstring(0, HashBytes('SHA1', @input), 1, 0))
  </code></pre>
  
  <p>but it calculates wrong hash when I replace first line of code with <code>declare @input nvarchar(50)</code>.</p>
  
  <pre><code>Calculated hash (nvarchar): BBA91B680CE2685E9465DE24967E425CF055B10F
  Calculated hash by a tool : 37AA63C77398D954473262E1A0057C1E632EDA77
  </code></pre>
  
  <p>How can I calculate <code>SHA1</code> hash of a <code>nvarchar</code> ?</p>
  
  <p>[EDIT]:</p>
  
  <p>Below C# code generate same hash as the tool I use for hashing:</p>
  
  <pre><code>// Computes SHA1 hash of a given string
  string ComputeHash(string input)
  {
      string result = string.Empty;
      byte[] hash;
      byte[] bytes = Encoding.GetBytes(input);
  
      using (var sha = SHA1Managed.Create())
          hash = sha.ComputeHash(bytes);
  
      foreach (var b in hash)
          result += b.ToString("X2");
  
      return result;
  }
  </code></pre>