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
?
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With