Convert MD5/SHA1 hash from binary to hex digest
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
an开发者_开发技巧d $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
}
say "digest_hex: $digest_hex;
say "digest_bin (as hex): ", unpack("H*", $digest_bin);
精彩评论