且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-03 21:57:22

您的代码中有一些问题。首先,当实现需要SHA1哈希的第一个十六个字节时,您的 $ secretKey 值被计算为填充的SHA1哈希值。

There are a number of problems in your code. First, your $secretKey value is computed as a padded SHA1 hash when the implementation requires the first sixteen bytes of the SHA1 hash.

$secretKey = substr(hash('sha1', $secretKey, true), 0, 16);

其次,您正在尝试执行秘密密钥的base64解码,这在这里无效。 mcrypt_encrypt()的第二个参数应为 $ sKey ,而不是 base64_decode($ sKey)

Second, you are trying to perform a base64 decode of the secret key, which is not valid here. The second argument to mcrypt_encrypt() should be $sKey, not base64_decode($sKey).

最后,如x77686d的答案中所述,您应该使用URL安全base64。这是base64的一个变体,它是未添加的,不使用 + / 字符。相反,在他们的地方使用 - _ 字符。

Finally, as explained in x77686d's answer, you should be using an "URL-safe" base64. That is a variation of base64 that is unpadded and does not use the + or / characters. Instead, the - and _ characters are used in their places.

ReCaptcha的安全令牌有点痛苦,老实说。它们是不安全的,算法是无证的。我一直和你一样,需要一个实现,所以我写了一个,并发表在 Packagist为slushie / recaptcha-secure-token。我建议使用它和/或贡献,只是因为缺少这种算法的替代实现。

ReCaptcha's secure tokens are a bit of a pain, honestly. They are insecure and the algorithm is undocumented. I've been in the same position as you and needed an implementation, so I wrote one and published it on Packagist as "slushie/recaptcha-secure-token". I'd recommend using it and/or contributing, if only because of the lack of alternative implementations of this algorithm.