title: SHA256 performance optimization in C
body: <p>I need to hash a big database of values quite often. Thus, a fast implementation of a SHA-2 hasher is needed. I'm currently using the SHA256.</p>
  
  <p>The sha256_transform algorithm I'm using right now is this:
  <a href="http://bradconte.com/sha256_c" rel="noreferrer">http://bradconte.com/sha256_c</a>
  (code below)</p>
  
  <p>I have profiled my code and this snippet is taking exactly 96% of computing time per hash, making this function critical to my goals.</p>
  
  <p>It operates on a 64-byte long binary string named <code>data[]</code> and outputs the result in <code>ctx->state</code>.</p>
  
  <p>I ask for a faster version of this function. Keep in mind that even slight modifications can impact speed negatively.</p>
  
  <pre><code>#define uchar unsigned char
  #define uint unsigned int
  
  #define ROTLEFT(a,b) (((a) &lt;&lt; (b)) | ((a) &gt;&gt; (32-(b))))
  #define ROTRIGHT(a,b) (((a) &gt;&gt; (b)) | ((a) &lt;&lt; (32-(b))))
  
  #define CH(x,y,z) (((x) &amp; (y)) ^ (~(x) &amp; (z)))
  #define MAJ(x,y,z) (((x) &amp; (y)) ^ ((x) &amp; (z)) ^ ((y) &amp; (z)))
  #define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22))
  #define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25))
  #define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) &gt;&gt; 3))
  #define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) &gt;&gt; 10))
  
  void sha256_transform(SHA256_CTX *ctx, uchar data[]) {
      uint a,b,c,d,e,f,g,h,i,j,t1,t2,m[64];
  
      a = ctx-&gt;state[0];
      b = ctx-&gt;state[1];
      c = ctx-&gt;state[2];
      d = ctx-&gt;state[3];
      e = ctx-&gt;state[4];
      f = ctx-&gt;state[5];
      g = ctx-&gt;state[6];
      h = ctx-&gt;state[7];
  
      for (i=0,j=0; i &lt; 16; i++, j += 4)
          m[i] = (data[j] &lt;&lt; 24) | (data[j+1] &lt;&lt; 16) | (data[j+2] &lt;&lt; 8) | (data[j+3]);
  
      for ( ; i &lt; 64; i++)
          m[i] = SIG1(m[i-2]) + m[i-7] + SIG0(m[i-15]) + m[i-16];
  
      for (i = 0; i &lt; 64; ++i) {
          t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i];
          t2 = EP0(a) + MAJ(a,b,c);
          h = g;
          g = f;
          f = e;
          e = d + t1;
          d = c;
          c = b;
          b = a;
          a = t1 + t2;
      }
  
      ctx-&gt;state[0] += a;
      ctx-&gt;state[1] += b;
      ctx-&gt;state[2] += c;
      ctx-&gt;state[3] += d;
      ctx-&gt;state[4] += e;
      ctx-&gt;state[5] += f;
      ctx-&gt;state[6] += g;
      ctx-&gt;state[7] += h;
  }
  </code></pre>