Google Authenticator implementation in Perl

后端 未结 4 922
無奈伤痛
無奈伤痛 2021-02-06 19:02

I am looking for a simple Perl implementation that verifies a Google authenticator token that has been created using a server side secret. For instance,

The following Go

4条回答
  •  误落风尘
    2021-02-06 19:29

    For posterity, I took the script from @Vijay's answer (thanks dude), simplified the algorithm a bit, added docs from TOTP definition, and added some sample code.

    The number generation code I whittled down to which is just a simplification of @Vijay's answer:

    use Digest::HMAC_SHA1 qw/ hmac_sha1_hex /;
    
    my $paddedTime = sprintf("%016x", int(time() / $TIME_STEP));
    my $data = pack('H*', $paddedTime);
    my $key = decode_base32($secret);
    
    # encrypt the data with the key and return the SHA1 of it in hex
    my $hmac = hmac_sha1_hex($data, $key);
    
    # take the 4 least significant bits (1 hex char) from the encrypted string as an offset
    my $offset = hex(substr($hmac, -1));
    # take the 4 bytes (8 hex chars) at the offset (* 2 for hex), and drop the high bit
    my $encrypted = hex(substr($hmac, $offset * 2, 8)) & 0x7fffffff;
    
    # the token is then the last 6 digits in the number
    my $token = $encrypted % 1000000;
    # make sure it is 0 prefixed
    return sprintf("%06d", $token);
    

    The full TOTP 2 Factor Auth Perl script can be downloaded from Github.

提交回复
热议问题