title: How to check formatting of a SHA-1 message-digest
body: <p>I need some basic validation (sanitation checks) to determine if some input is a valid SHA1 sum or just a (random) string. If possible with simple parsing rules or a Regex.</p>
  
  <p>Are there any rules to what a SHA1 sum should adhere? I cannot find any, but from quick tests, all seem to be hexadecimal and around 40 characters long[1].</p>
  
  <p>I am not interested in tests that prove whether or not the SHA-1 sum was made in a secure, properly random or other manner. Just that the format is correct.</p>
  
  <p>I am also not interested in testing that the digest is an actual representation of some message; Just that it has the format of digest in the first place.</p>
  
  <hr>
  
  <p>For the curious: this is for an application where I build avatars for users based on a.o. their uuid. I don't, however, want to place those uuids in the URL, but obfuscate them a little. So instead of <code>avatars/baa4833d-b962-4ab1-87c5-283c9820eac4.png</code>, we request <code>avatars/5f2a13cb1d84a2e019842cdb8d0c8b03c9e1e414.png</code>. Where <code>5f2a...</code> is e.g. <code>Digest::SHA1.hexdigest(uuid + "secrect")</code>. </p>
  
  <p>On the receiving side, I am adding some basic protection that sends back a <code>400 bad request</code> whenever something is obviously false. Such as <code>avatars/haxor.png</code> or <code>avatars/traversal../../../../attempt.png</code>. Note that this is a very much simplified example.</p>
  
  <hr>
  
  <p>[1] Two tests with different outcome:</p>
  
  <p>Using <code>sha1sum</code> on Ubuntu Linux: </p>
  
  <pre><code>$ echo "hello" | sha1sum | cut -d" " -f1 | wc -c
  41
  </code></pre>
  
  <p>using Ruby's Digest:   </p>
  
  <pre><code>Digest::SHA1.hexdigest("hello").length
  =&gt; 40
  </code></pre>
  
  <p>Edit: turns out this is me, being stupid, wc-c includes the newline, as <em>kennytm</em> points out in the comments. Still: is it safe to assume it will be 40 characters, always?</p>