Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert MD5/SHA1 hash from binary to hex digest

Tags:

hash

md5

perl

I am looking for a way to convert MD5 and SHA1 hashes from their binary to hex representations and vice versa. I want to do it in Perl but a common explaination is welcome too.

use Digest::MD5 qw(md5 md5_hex md5_base64);
$data = "Plaintext";
$digest_bin = md5($data);
$digest_hex = md5_hex($data);

How can I compare $digest_bin and $digest_hex and make sure that they are hashes of the same $data?

like image 224
sw0x2A Avatar asked Dec 06 '22 20:12

sw0x2A


2 Answers

unpack("H*", md5($x)) eq md5_hex($x); 
pack("H*", md5_hex($x)) eq md5($x);

perldoc -f pack

The "H*" argument is used to translate a string of bytes into their hex representation and vice versa.

like image 53
Dallaylaen Avatar answered Jan 06 '23 01:01

Dallaylaen


If you look into the source of Digest::MD5::Perl, which is the pure perl version of Digest::MD5, you'll see:

sub _encode_hex { unpack 'H*', $_[0] }    
sub md5_hex { _encode_hex &md5 }

So you can do:

if ($digest_hex eq unpack 'H*', $digest_bin) {
    # same data
}
like image 45
Eugene Yarmash Avatar answered Jan 06 '23 00:01

Eugene Yarmash