From c7051644fb4cce7f3adaa6d20aed7c0c17e057b2 Mon Sep 17 00:00:00 2001
From: Filippo Tessarotto <zoeslam@gmail.com>
Date: Thu, 13 Oct 2022 15:24:57 +0200
Subject: [PATCH] Single point of secret creation

---
 phpstan.neon | 1 +
 src/HOTP.php | 5 +----
 src/OTP.php  | 8 ++++++++
 src/TOTP.php | 5 +----
 4 files changed, 11 insertions(+), 8 deletions(-)

diff --git a/phpstan.neon b/phpstan.neon
index 9cb0a82..e55b635 100644
--- a/phpstan.neon
+++ b/phpstan.neon
@@ -5,6 +5,7 @@ parameters:
         - tests
     ignoreErrors:
         - '#Variable property access on \$this\(OTPHP\\OTP\)\.#'
+        - '#^Method OTPHP\\OTP::generateSecret\(\) should return non-empty-string but returns string\.$#'
 
 includes:
     - vendor/phpstan/phpstan-strict-rules/rules.neon
diff --git a/src/HOTP.php b/src/HOTP.php
index b717e13..dd297ac 100644
--- a/src/HOTP.php
+++ b/src/HOTP.php
@@ -6,7 +6,6 @@ namespace OTPHP;
 
 use InvalidArgumentException;
 use function is_int;
-use ParagonIE\ConstantTime\Base32;
 
 /**
  * @see \OTPHP\Test\HOTPTest
@@ -39,9 +38,7 @@ final class HOTP extends OTP implements HOTPInterface
 
     public static function generate(int $counter = 0, string $digest = 'sha1', int $digits = 6): self
     {
-        $secret = Base32::encodeUpper(random_bytes(64));
-
-        return new self($secret, $counter, $digest, $digits);
+        return new self(self::generateSecret(), $counter, $digest, $digits);
     }
 
     public function getCounter(): int
diff --git a/src/OTP.php b/src/OTP.php
index f590668..d51ea7b 100644
--- a/src/OTP.php
+++ b/src/OTP.php
@@ -36,6 +36,14 @@ abstract class OTP implements OTPInterface
         return $this->generateOTP($input);
     }
 
+    /**
+     * @return non-empty-string
+     */
+    final protected static function generateSecret(): string
+    {
+        return Base32::encodeUpper(random_bytes(64));
+    }
+
     /**
      * The OTP at the specified input.
      */
diff --git a/src/TOTP.php b/src/TOTP.php
index 3835881..61b8104 100644
--- a/src/TOTP.php
+++ b/src/TOTP.php
@@ -6,7 +6,6 @@ namespace OTPHP;
 
 use InvalidArgumentException;
 use function is_int;
-use ParagonIE\ConstantTime\Base32;
 
 /**
  * @see \OTPHP\Test\TOTPTest
@@ -46,9 +45,7 @@ final class TOTP extends OTP implements TOTPInterface
         int $digits = 6,
         int $epoch = 0
     ): self {
-        $secret = Base32::encodeUpper(random_bytes(64));
-
-        return new self($secret, $period, $digest, $digits, $epoch);
+        return new self(self::generateSecret(), $period, $digest, $digits, $epoch);
     }
 
     public function getPeriod(): int
-- 
GitLab