master
ブランチ master
LittleBeast / src / Std / Lib / Totp.php
5 KB、113行 生 Blame 履歴
1<?php
2/*************************************************************
3# 076 License
4
5Copyright (c) テクニカル諏訪子
6
7Permission is hereby granted to any person obtaining a copy of the software
8Little Beast (the "Software") to use, modify, merge, copy, publish, distribute,
9sublicense, and/or sell copies of the Software, subject to the following conditions:
10
11 1. **Origin Attribution**:
12 - You must not misrepresent the origin of the Software; you must not claim
13 you created the original Software.
14 - If the Software is used in a product, you must either:
15 a. Provide clear attribution in the product's documentation, user interface,
16 or other visible areas, **OR**
17 b. Pay the original developers a fee they specify in writing.
18 2. **Usage Restriction**:
19 - The Software, or any derivative works, dependencies, or libraries
20 incorporating it, must not be used for censorship or to suppress freedom of
21 speech, expression, or creativity. Prohibited uses include, but are not
22 limited to:
23 - Censorship of so-called "hate speech", visuals, non-mainstream opinions,
24 ideas, or objective reality.
25 - Tools or systems designed to restrict access to information or
26 artistic works.
27 3. **Notice Preservation**:
28 - This license and the above copyright notice must remain intact in all copies
29 of the source code.
30
31THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
32INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
33PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
34HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
35CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
36OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 */
38namespace Std\Lib;
39
40/**
41 * ワンタイムパスワード(HOTP:RFC 4226、TOTP:RFC 6238)
42 *
43 * 認証アプリ(Google Authenticator、Aegis、KeePassXC等)と同じ既定(SHA-1、6桁、30秒)を使う。
44 * 秘密鍵はBase32の文字列で扱う。
45 */
46final class Totp {
47 public const DIGITS = 6;
48 public const PERIOD = 30;
49
50 /**
51 * 新しい秘密鍵(既定は160ビット、Base32で32文字)
52 */
53 public static function secret(int $bytes = 20): string {
54 return BaseN::encode32(random_bytes($bytes), false);
55 }
56
57 /**
58 * HOTPの値
59 *
60 * @param string $key 秘密鍵(Base32ではなく元のバイト列)
61 * @param string $algo sha1・sha256・sha512
62 */
63 public static function hotp(#[\SensitiveParameter] string $key, int $counter, int $digits = self::DIGITS, string $algo = 'sha1'): string {
64 $h = hash_hmac($algo, pack('J', $counter), $key, true);
65 $o = ord($h[strlen($h) - 1]) & 0x0f;
66 $bin = ((ord($h[$o]) & 0x7f) << 24) | (ord($h[$o + 1]) << 16) | (ord($h[$o + 2]) << 8) | ord($h[$o + 3]);
67 return str_pad((string)($bin % (10 ** $digits)), $digits, '0', STR_PAD_LEFT);
68 }
69
70 /**
71 * 時刻のTOTPの値
72 *
73 * @param string $secret Base32の秘密鍵
74 * @param int|null $time UNIX時間(既定は今)
75 */
76 public static function code(#[\SensitiveParameter] string $secret, ?int $time = null, int $digits = self::DIGITS, int $period = self::PERIOD, string $algo = 'sha1'): string {
77 return self::hotp(BaseN::decode32($secret), intdiv($time ?? time(), $period), $digits, $algo);
78 }
79
80 /**
81 * コードを確かめる(時計のずれの為、前後$window個の時間も認める)
82 *
83 * @param int $lastStep 前回使った時間の番号(同じコードを2度使えない様に、それ以前は認めない)
84 * @return int|null 一致した時間の番号(次のlastStepとして保存する)、一致しなければnull
85 */
86 public static function verify(#[\SensitiveParameter] string $secret, string $code, int $lastStep = -1, ?int $time = null, int $window = 1): ?int {
87 $code = preg_replace('/\s+/', '', $code);
88 if (!preg_match('/^\d{'.self::DIGITS.'}$/', $code)) return null;
89 try {
90 $key = BaseN::decode32($secret);
91 } catch (\InvalidArgumentException $e) {
92 return null;
93 }
94 $now = intdiv($time ?? time(), self::PERIOD);
95 $found = null;
96 // 一致しても最後まで比べる(時間で分からない様に)
97 for ($step = $now - $window; $step <= $now + $window; $step++) {
98 if (hash_equals(self::hotp($key, $step), $code) && $step > $lastStep && $found === null) $found = $step;
99 }
100 return $found;
101 }
102
103 /**
104 * 認証アプリに登録するURI(QRコードにする)
105 *
106 * @param string $account ユーザー名等
107 * @param string $issuer サイトの名前
108 */
109 public static function uri(#[\SensitiveParameter] string $secret, string $account, string $issuer): string {
110 $label = rawurlencode($issuer).':'.rawurlencode($account);
111 return 'otpauth://totp/'.$label.'?secret='.rtrim($secret, '=').'&issuer='.rawurlencode($issuer).'&algorithm=SHA1&digits='.self::DIGITS.'&period='.self::PERIOD;
112 }
113}