Convert MD5 / SHA1 hash from binary to hexadecimal digest

I am looking for a way to convert MD5 and SHA1 hashes from their binary to hexadecimal representations and vice versa. I want to do this in Perl, but a general explanation is also welcome.

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

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

+4
source share
3 answers

If you look at the source of Digest :: MD5 :: Perl, which is a pure Perl version of Digest :: MD5, you will 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 } 
+5
source
 unpack("H*", md5($x)) eq md5_hex($x); pack("H*", md5_hex($x)) eq md5($x); 

perldoc -f pack

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

+10
source
 say "digest_hex: $digest_hex; say "digest_bin (as hex): ", unpack("H*", $digest_bin); 
0
source

All Articles