title: openssl sha1 giving different results in the terminal vs in Python
body: <p>I am trying to run an openssl command from a Python script, but am getting different sha1 values from the command executed in the script and the command executed directly in the terminal.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>command = "echo -n '" + hex(key)[2:] + "' | openssl sha1"
  print(command)
  os.system(command)
  output = subprocess.check_output(command, shell=True)
  # This converts the bytes object to a string.
  output = output.decode("utf-8")
  print(output)
  </code></pre>
  
  <p>The <code>os.system(command)</code> is only there to check whether this method and <code>subprocess.check_output()</code> give the same result.</p>
  
  <p>Here is the program output for an example input of <code>key=0xabc</code>:</p>
  
  <pre><code>echo -n 'abc' | openssl sha1
  (stdin)= 9d4fe92b8bdc894f5838fad83108bf3841b257fa
  (stdin)= 9d4fe92b8bdc894f5838fad83108bf3841b257fa
  </code></pre>
  
  <p>The first line is the command to be executed, the second is the result of the command using os.system() and the third is the result of the command using subprocess.check_output(). As you can see, both methods give the same result.</p>
  
  <p>Now, if I copy and paste the command as it is displayed here and execute it in the terminal, this is the result:</p>
  
  <pre><code>(stdin)= a9993e364706816aba3e25717850c26c9cd0d89d
  </code></pre>
  
  <p>Even though I copy and pasted the exact same command, the hash value output is different.</p>
  
  <p>Even stranger, if I omit the <code>-n</code> option from <code>echo</code>, there is no inconsistency:</p>
  
  <pre><code>echo 'abc' | openssl sha1
  (stdin)= 03cfd743661f07975fa2f1220c5194cbaff48451
  (stdin)= 03cfd743661f07975fa2f1220c5194cbaff48451
  </code></pre>
  
  <p>And in the terminal:</p>
  
  <pre><code>(stdin)= 03cfd743661f07975fa2f1220c5194cbaff48451
  </code></pre>
  
  <p>Everything I have read online about similar issues stems from not using <code>-n</code>, rather than <code>-n</code> seemingly causing the issue. For the particular task I am doing, I have to use <code>-n</code> as I am computing the pre-image of a hash which was calculated using <code>echo -n "hash_value" | openssl sha1</code>.</p>
  
  <p>Any help would be much appreciated :)</p>