如何使用Perl生成Google ReCaptcha V2安全令牌?

时间:2015-08-18 10:08:33

标签: perl security encryption token recaptcha

我正在尝试使用perl的google安全令牌,如链接中所述 https://developers.google.com/recaptcha/docs/secure_token

然而,它总是会引发安全令牌无效。 我也检查了这个链接,但没有成功 https://stackoverflow.com/questions/31478724/how-to-generate-a-google-recaptcha-v2-secure-token-with-php

#!/usr/bin/perl

use Data::UUID;
use JSON;
use Time::HiRes qw/gettimeofday/;
use MIME::Base64::URLSafe;
use Digest::SHA1  qw(sha1 sha1_hex sha1_base64);
use Crypt::Rijndael;

use constant PUBLIC_KEY  => '...';
use constant PRIVATE_KEY => '...';

my $public_key = PUBLIC_KEY;

print "Content-type: text/html;charset=UTF-8\n\n";

my $uuid = Data::UUID->new();

my $uuid1 = $uuid->create_str();
my $uuidstr = $uuid->to_string( $uuid );

my $seconds = gettimeofday(); #in scalar context it returns a
my $ms      = int($seconds*1000);

my %hash;

$hash{'session_id'} = $uuidstr;
$hash{'timestamp'} = $ms;

my $json = JSON->new->allow_nonref;
my $json_text = $json->encode(\%hash);
$json_text =~ s/"//g;

my $sha_one = sha1(PRIVATE_KEY);
my $new_secret_key = substr $sha_one, 0, 16;

my $block_size = 16;
my $pad = $block_size - ((length $json_text) % $block_size);
my $append_str = $pad x $pad;

$json_text = $json_text . $append_str;

my $cipher = Crypt::Rijndael->new($new_secret_key, Crypt::Rijndael::MODE_ECB);
my $cipher_text = $cipher->encrypt($json_text);
my $encoded_text = urlsafe_b64encode($cipher_text);

print <<EOT;
<html>
<head>
  <script src='//www.google.com/recaptcha/api.js'></script>
</head>
<body>
  <form>
    <div class="g-recaptcha" data-sitekey="$public_key" data-stoken="$encoded_text"></div>
  </form>
</body>
</html>
EOT

有人能指出我的代码中的任何明显错误或建议一些已经存在的perl代码吗?

1 个答案:

答案 0 :(得分:1)

我从你的代码开始,但结果却有些不同。我不是加密专家,所以我不确定为什么我的方法有效而你的方法没有。但这就是我所拥有的 - 它确实有效:

obj.dig(:a, :b, :c)

我基本上将this php library转换为粗糙的perl以使其工作。