sha1 question

What is the unix shell scripting equivalent of the following php code? I have tried to reproduce it, but I haven't been able to.

<?php
sha1(sha1(strtolower($user) . $pass) . $sessionid);
?>

What OS and shell are you using?

I use ubuntu linux.

The latest Ubuntu uses bash4, so you could use something like this:

$ user=MyUser pass=mypass sessionid=mysessionid
$ _sha1=$(sha1sum <<< "$(sha1sum <<< "${user,,}$pass")$sessionid")
$ printf '%s\n' ${_sha1% *}
91aacc49855185f87659ffd87b8b4944c4822412

These two scripts don't seem to match, so I don't know what I have done wrong.

<?php
$sessionid='mysessionid';
$user='myuser';
$pass='mypass';
$_sha = sha1(sha1(strtolower($user) . $pass) . $sessionid);
echo "$sha_pass\n";
?>
user="myuser"
pass="mypass"
sessionid="mysessionid"
_sha1=$(sha1sum <<< "$(sha1sum <<< "${user,,}$pass")$sessionid")
echo $_sha1

test:
laptop:~$ printf '%s\n' ${_sha1% *}
bf281edee15d125685d4a26f9542e9d1103aa218
laptop:~$ php shapass.php
27fe0e704617028883596d167f151d5a1a189dbd

My sh script version agrees with the php version. Also, while I'm not very familiar with bash 4, it seems to me that the outermost pair of double quotes is off (the pair cross a command substitution boundary).

$ printf %s%s $(printf %s%s "$(printf %s MyUser | tr '[:upper:]' '[:lower:]')" mypass | openssl sha1) mysessionid | openssl sha1

27fe0e704617028883596d167f151d5a1a189dbd

Regards,
Alister

---------- Post updated at 05:33 PM ---------- Previous update was at 05:30 PM ----------

Woops! Disregard my comment regarding the quoting in the bash 4 code. I misread it. :slight_smile:

this works! thank you!

My code is wrong, the here-string, <<< string , adds a trailing newline.

This should be OK (it still requires bash4,in order to avoid the call to another external command):

user=MyUser pass=mypass sessionid=mysessionid
_sha1=$(printf %s "${user,,}$pass"|sha1sum)
_sha1=${_sha1% *}$sessionid _sha1=$(printf %s $_sha1|sha1sum)
printf '%s\n' ${_sha1% *}

This works for bash 3 and later.

#!/bin/bash

user=MyUser pass=mypass sessionid=mysessionid

user=$(echo $user | tr '[:upper:]' '[:lower:]')

_sha1=$(printf %s%s $user $pass | sha1)
_sha1=$(printf %s%s ${_sha1}${sessionid} | sha1)

printf '%s\n' ${_sha1}

Hi, fpmurphy:

The original php code does not modify $pass, so it should not be piped through tr.

Regards,
Alister

Err, does not give correct solution unless the pipe is there. And I am not modifying $pass!

It works with that sample data because $pass is all lower case, but if there were an upper case character in $pass, the result would be incorrect.

1 Like

Ah, well spotted. You are correct. I will fix my example code.