4

I have a PHP application that has passwords stored in the database as the output of sha1($password), which is apparently the hex representation of the binary SHA1 hash. (as I understand it)

I would like to convert that to a format that is compatible for Apache .htpassword files, which needs to be the base64 encoded binary value or the output of base64_encode(sha1($password, true)).

I found this thread: Convert base64'd SHA1 hashes to Hex hashes ... which is doing the opposite of what I need to do, and it works great. I tried to change the ordering of the commands and use hex2bin instead of bin2hex, but that doesn't work:

Fatal error: Call to undefined function hex2bin() in php shell code on line 1

Apparently that is not available until PHP 5.4, and this server is still on 5.3.x http://php.net/manual/en/function.hex2bin.php

Here is the real problem. I actually need it to convert in PERL, preferably only using standard built-in modules to keep everything simple. I am not sure why they are using perl for this step, but I am trying to edit one very small part of a larger application and don't want to change the whole thing yet :)

To be clear, I am not trying to convert hex numbers to binary numbers. This is a hex representation of a binary value, stored in a perl "string" :)

Thanks in advance, Tommy

Community
  • 1
  • 1
TommyTheKid
  • 166
  • 2
  • 10

1 Answers1

6

You explain so much but still leave me unsure as to what you want :/

If what you want is to convert from a hex string to a blob to base64 string, which is what you say you want in the top paragraph of your question,

use MIME::Base64;
my $bin = pack "H*", $hex_str;
my $encoded = encode_base64($bin);

which exactly matches what you want: base64_encode(sha1($password, true))

Ignore my previous answers and edits.

Jarrod Funnell
  • 721
  • 4
  • 11
  • Wow, thanks! Perfect! I have tested the solution and it looks good. I will implement it and see how it works (or whether it is accepted upstream) ;) EDIT: I will vote it up when they let me :) – TommyTheKid Jul 08 '12 at 13:26
  • For what its worth, I also had to use `chomp($encoded)` to get rid of an extra newline, but its working, and here is the [result](https://github.com/TJM/nconf/compare/HandleApacheSHA1) ... not sure how long it will last as a link tho :) – TommyTheKid Jul 08 '12 at 15:02
  • Huh.. I never even noticed encode_base64 added a newline. We all learned something. – Jarrod Funnell Jul 09 '12 at 09:31