RobThree\Auth\TwoFactorAuth::createSecret PHP Method

createSecret() public method

Create a new secret
public createSecret ( $bits = 80, $requirecryptosecure = true )
    public function createSecret($bits = 80, $requirecryptosecure = true)
    {
        $secret = '';
        $bytes = ceil($bits / 5);
        //We use 5 bits of each byte (since we have a 32-character 'alphabet' / BASE32)
        if ($requirecryptosecure && !$this->rngprovider->isCryptographicallySecure()) {
            throw new TwoFactorAuthException('RNG provider is not cryptographically secure');
        }
        $rnd = $this->rngprovider->getRandomBytes($bytes);
        for ($i = 0; $i < $bytes; $i++) {
            $secret .= self::$_base32[ord($rnd[$i]) & 31];
        }
        //Mask out left 3 bits for 0-31 values
        return $secret;
    }

Usage Example

 public function testCreateSecretGeneratesDesiredAmountOfEntropy()
 {
     $rng = new TestRNGProvider(true);
     $tfa = new TwoFactorAuth('Test', 6, 30, 'sha1', null, $rng);
     $this->assertEquals('A', $tfa->createSecret(5));
     $this->assertEquals('AB', $tfa->createSecret(6));
     $this->assertEquals('ABCDEFGHIJKLMNOPQRSTUVWXYZ', $tfa->createSecret(128));
     $this->assertEquals('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', $tfa->createSecret(160));
     $this->assertEquals('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', $tfa->createSecret(320));
     $this->assertEquals('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567ABCDEFGHIJKLMNOPQRSTUVWXYZ234567A', $tfa->createSecret(321));
 }
All Usage Examples Of RobThree\Auth\TwoFactorAuth::createSecret