From d88cc57a7495b77147ed685a79e14b9980077367 Mon Sep 17 00:00:00 2001 From: Andrew Brown Date: Tue, 23 Jan 2024 15:14:10 -0600 Subject: [PATCH] allow passing a `$secretSize` when generating a secret this will allow the user to set their own secret length, but allow the package to still handle the creation of the string. I think this is a better interface for the user, as this is most likely a large chunk of the reasons someone would want to have a custom secret over the default. It also helps avoid a (likely) implicit dependency in user code. We are currently using `TOTP::createFromSecret(Base32::encode(Str::random(16)))->getSecret()` to generate a shorter random secret than the default. Here we are using the `Base32` class from `ParagonIE`, even though it is not an explicit dependency in our code. We probably should be, rather than implicitly depend on it. I'm guessing other people may make this mistake as well. --- src/HOTP.php | 4 ++-- src/OTP.php | 4 ++-- src/TOTP.php | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/HOTP.php b/src/HOTP.php index e6bea73..adcbdfa 100644 --- a/src/HOTP.php +++ b/src/HOTP.php @@ -41,9 +41,9 @@ public static function createFromSecret(string $secret): self return $htop; } - public static function generate(): self + public static function generate(int $secretSize = null): self { - return self::createFromSecret(self::generateSecret()); + return self::createFromSecret(self::generateSecret($secretSize)); } public function getCounter(): int diff --git a/src/OTP.php b/src/OTP.php index 49e1730..0f981d2 100644 --- a/src/OTP.php +++ b/src/OTP.php @@ -43,9 +43,9 @@ public function at(int $input): string /** * @return non-empty-string */ - final protected static function generateSecret(): string + final protected static function generateSecret(int $secretSize = null): string { - return Base32::encodeUpper(random_bytes(self::DEFAULT_SECRET_SIZE)); + return Base32::encodeUpper(random_bytes($secretSize ?? self::DEFAULT_SECRET_SIZE)); } /** diff --git a/src/TOTP.php b/src/TOTP.php index 6bc87ee..beb1611 100644 --- a/src/TOTP.php +++ b/src/TOTP.php @@ -62,9 +62,9 @@ public static function createFromSecret(string $secret, ?ClockInterface $clock = return $totp; } - public static function generate(?ClockInterface $clock = null): self + public static function generate(?ClockInterface $clock = null, int $secretSize = null): self { - return self::createFromSecret(self::generateSecret(), $clock); + return self::createFromSecret(self::generateSecret($secretSize), $clock); } public function getPeriod(): int