【问题标题】:PHP - Google Authenticator URI codes don't always workPHP - Google Authenticator URI 代码并不总是有效
【发布时间】:2019-01-30 07:57:17
【问题描述】:

所以我在使用 google 身份验证器和我的 PHP 时遇到了问题。

所以我使用这个库来生成二维码:https://github.com/PHPGangsta/GoogleAuthenticator

因此,当我使用我的用户名生成代码时,它可以正常工作。我得到了一些类似的东西: otpauth://totp/username?secret=aCodeInBase32&issuer=Mysite

就我而言,它是: otpauth://totp/NoahNok?secret=aCodeInBase32&issuer=Mysite

但是,在为任何其他用途执行此操作时,我在 Google Authenticator 应用程序上收到无效令牌错误。不管我放什么其他东西,我似乎总是收到这个错误,但它对我的帐户来说很好。

例如,这个不起作用:otpauth://totp/Test?secret=KRSX&issuer=MySite

有什么明显的我做错了吗?

代码即时使用: 获取数据之前的一些查询

$g = new PHPGangsta_GoogleAuthenticator();
include("Base32.php");
$secret = substr(Base32::encode($username),0,-4);
echo $g->getQRCodeGoogleUrl($username, $secret, "MySite");

生成二维码网址

    public function getQRCodeGoogleUrl($name, $secret, $title = null, $params = array())
{
    $width = !empty($params['width']) && (int) $params['width'] > 0 ? (int) $params['width'] : 200;
    $height = !empty($params['height']) && (int) $params['height'] > 0 ? (int) $params['height'] : 200;
    $level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M';

    $urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.'');
    if (isset($title)) {
        $urlencoded .= urlencode('&issuer='.urlencode($title));
    }

    return 'https://chart.googleapis.com/chart?chs='.$width.'x'.$height.'&chld='.$level.'|0&cht=qr&chl='.$urlencoded.'';
}

【问题讨论】:

标签: php google-authenticator


【解决方案1】:

Base32 被填充到最接近的 8 个字符的倍数,因此它不会总是在末尾有 ==== 以剥离。从你的例子我们得到:

NoahNok => JZXWC2CON5VQ====

和:

Test => KRSXG5A=

因此,如果您始终删除最后 4 个字符,您将在后一种情况下创建无效的 Base32 序列。您可以改为使用rtrim,如下所示:

$secret = rtrim(Base32::encode($username), '=')

仅删除所有尾随等于(或仅保留它们)。

编辑

我只是在考虑这个问题,虽然上面的方法可以解决最近的问题,但以这种方式生成秘密可能不是一个好主意。如果您考虑一下,将秘密设置为用户名意味着如果有人找到用户名,他们可以生成有效的 OTP,从而能够通过他们的 2FA。

Secret 应该是唯一的,并且通常不能用于此目的,并且您使用的库有一个 createSecret 方法可以为您执行此操作。

【讨论】:

  • 谢谢,您解决了我的问题,我改用安全密钥。
猜你喜欢
  • 2014-06-25
  • 2022-01-19
  • 2016-05-29
  • 2021-08-17
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2020-08-25
相关资源
最近更新 更多