首页 > 解决方案 > phpqrcode 和 google 身份验证器 - 不确定事物的格式以及如何使其正确验证

问题描述

我正在使用phpqrcode创建一个用于两因素身份验证的 qrcode。我一直使用 Google Authenticator 应用程序来满足我所有的 2FA 需求。虽然我可以创建 qrcode,但我不确定确切的格式,因此它可以正确验证。截至目前,当我尝试扫描它时,我会从应用程序中返回“无效条形码”。

生成 qrcode 时,我是使用密钥、url 还是两者的组合?我错过了一些愚蠢的东西,我确定这是因为我不明白在哪里以及如何使用 params 和 otpauth:// url。

require $_SERVER['DOCUMENT_ROOT'].'/assets/phpqrcode/phpqrcode.php';

//get params
$secret = create2FASecret();
$name = 'somename';
$issuer = 'example.com';

//url encode, but not sure where or how I use this
$urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.'&issuer='.$issuer.'');

//create the qrcode, base64 it, output it
ob_start();
QRCode::png($urlencoded, null, QR_ECLEVEL_L, 3, 4);
$newpng = base64_encode( ob_get_contents() );
ob_end_clean();

$src = 'data: image/png; base64,'.$newpng;


//show secret created and the qrcode
echo 'This is the secret that was generated : '.$secret,'<br>';
echo '<img src="' . $src . '" />';

//create a secret
function create2FASecret($secretLength = 16)
{
    $validChars = array(
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //  7
        'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23
        'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31
        '='  // padding char
    );
    
    unset($validChars[32]);

    $secret = '';
    for ($i = 0; $i < $secretLength; $i++) {
        $secret .= $validChars[array_rand($validChars)];
    }
    return $secret;
}

标签: phpqr-codetwo-factor-authenticationgoogle-2fa

解决方案


事实证明 - 只有 $name 和 $issuer 应该被 urlencoded 并且它可以正常工作。我还根据https://github.com/google/google-authenticator/wiki/Key-Uri-Format更改了 url 的格式

$name = urlencode($name);
$issuer = urlencode($issuer);

//%3A is encoded colon
$url = 'otpauth://totp/'.$issuer.'%3A'.$name.'?secret='.$secret.'&issuer='.$issuer.'&algorithm=SHA1&digits=6&period=30';


//create the qrcode, base64 it, output it
ob_start();
QRCode::png($url, null, QR_ECLEVEL_L, 3, 4);
$newpng = base64_encode( ob_get_contents() );
ob_end_clean();

推荐阅读