From 65da89746b2220fa5740a97a1e07799b37d13535 Mon Sep 17 00:00:00 2001 From: Niklas Keller Date: Mon, 13 Jun 2016 09:37:42 +0200 Subject: [PATCH] Add Oath::encodeKey to show secrets for manual setup without QR code --- README.md | 8 ++++++++ src/Oath.php | 12 ++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9c558cb..249e28f 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,10 @@ There's a [runnable demo](./examples/demo.php) contained in this repository. ```php $oath = new Oath; + +// this generates a key in binary format $key = $oath->generateKey(); + // store key for user ``` @@ -35,7 +38,12 @@ $key = $oath->generateKey(); ```php $oath = new Oath; $key = "..."; // load user key from storage + +// Use the URI to provide an easy to scan QR code $uri = $oath->getUri($key); + +// Alternatively display the key for manual input +$secret = $oath->encodeKey($key); ``` You can use your favourite JavaScript or PHP library to generate the QR code. For a working example, we're using [`qr.js`](http://neocotic.com/qr.js/). diff --git a/src/Oath.php b/src/Oath.php index ef70e95..0492005 100644 --- a/src/Oath.php +++ b/src/Oath.php @@ -33,6 +33,14 @@ public function generateKey($length = 20) { return random_bytes($length); } + public function encodeKey($key) { + if (!is_string($key)) { + throw new \InvalidArgumentException("Key must be string"); + } + + return Base32::encode($key); + } + public function generateHotp($key, $counter) { if (!is_string($key)) { throw new \InvalidArgumentException("Key must be string"); @@ -121,7 +129,7 @@ public function getUri($key, $issuer, $account) { return "otpauth://totp/" . urlencode($issuer) . ":" . urlencode($account) . "?" . http_build_query([ "algorithm" => "SHA1", - "secret" => Base32::encode($key), + "secret" => $this->encodeKey($key), "digits" => $this->length, "period" => $this->windowSize, "issuer" => $issuer, @@ -152,4 +160,4 @@ private function oathTruncate($rawHmac) { // And extract HOTP value according to OTP_LENGTH return ($p[1] & 0x7FFFFFFF) % pow(10, $this->length); } -} \ No newline at end of file +}