简体   繁体   中英

Why mysql and perl base64 string encoding is different?

#!/usr/bin/env perl
use Digest;
say Digest->new( 'SHA-1' )->add('test')->b64digest; # qUqP5cyxm6YcTAhz05Hph5gvu9M


SELECT TO_BASE64(SHA1('test')); # YTk0YThmZTVjY2IxOWJhNjFjNGMwODczZDM5MWU5ODc5ODJmYmJkMw==

So same ASCII word test encoded as qUqP5cyxm6YcTAhz05Hph5gvu9M in Perl and as YTk0YThmZTVjY2IxOWJhNjFjNGMwODczZDM5MWU5ODc5ODJmYmJkMw== in MySQL.

Why?

As pointed out by Raymond, you're looking at the results of two different calculations.

Your perl prints out the base64 encoded SHA-1 digest of "test" . Your MySQL query takes the base16 encoded SHA-1 digest of "test" and then base64 encodes that string.

Consider a perl one-liner that does the same two steps as the SELECT :

$ perl -MDigest -MMIME::Base64 -E 'say encode_base64(Digest->new("SHA-1")->add("test")->hexdigest)'
YTk0YThmZTVjY2IxOWJhNjFjNGMwODczZDM5MWU5ODc5ODJmYmJkMw==

and the MySQL query

SELECT to_base64(unhex(sha1('test')))

which gives qUqP5cyxm6YcTAhz05Hph5gvu9M= , like your perl but with padding added.

I'd stick with base16/hex versions, though, as that's what people are used to seeing for digests: a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 for the SHA-1 of "test" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM