title: Why do I sometimes get different SHA256 hashes in Java and PHP?
body: <p>So I have an odd little problem with the hashing function in PHP. It only happens some of the time, which is what is confusing me. Essentially, I have a Java app and a PHP page, both of which calculate the SHA256 of the same string. There hasn't been any issues across the two, as they calculate the same hash (generally). The one exception is that every once in a while, PHP's output is one character longer than Java's.</p>
  
  <p>I have this code in PHP:</p>
  
  <pre><code>$token = $_GET["token"];
  $token = hash("sha256", $token."&lt;salt&gt;");
  echo "Your token is " . $token;
  </code></pre>
  
  <p>99% of the time, I get the right hash. But every once in a while, I get something like this (space added to show the difference):</p>
  
  <pre><code>26be60ec9a36f217df83834939cbefa33ac798776977c1970f6c38ba1cf92e92 # PHP
  26be60ec9a36f217df83834939cbefa33ac798776977c197 f6c38ba1cf92e92 # Java
  </code></pre>
  
  <p>As you can see, they're nearly identical. But the top one (computed by PHP) has one more 0 for some reason. I haven't really noticed a rhyme or reason to it, but it's certainly stumped me. I've tried thinking of things like the wrong encoding, or wrong return value, but none of them really explain why they're almost identical except for that one character.</p>
  
  <p>Any help on this issue would be much appreciated.</p>
  
  <p>EDIT: The space is only in the bottom one to highlight where the extra 0 is. The actual hash has no space, and is indeed a valid hash, as it's the same one that Java produces.</p>
  
  <p>EDIT2: Sorry about that. I checked the lengths with Notepad++, and since it's different than my normal text editor, I misread the length by 1. So yes, the top one is indeed right. Which means that it's a bug in my Java code. I'm going to explore Ignacio's answer and get back to you.</p>