phpqr-codetwo-factor-authenticationgoogle-2fa

phpqrcode and google authenticator - not sure of the format of things and how to get it to validate correctly


I am using phpqrcode to create a qrcode for use with two-factor authentication. I have always used the Google Authenticator app for all my 2FA needs. While I can create the qrcode I am not sure of the exact format so it validates correctly. As of now when I try to scan it I get 'invalid barcode' back from the app.

Do I use the secret, the url, or combination of both when generating the qrcode? I'm missing something stupid and I'm sure it's because I don't understand where and how to use the params and 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;
}

Solution

  • As it turns out - only the $name and $issuer should be urlencoded and it works as it should. I also changed the format of the url according to https://github.com/google/google-authenticator/wiki/Key-Uri-Format

    $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();