Debian Codegraph @

vendor/jakobo/hotp-php/src/HOTPResult.php

raw
1 <?php
2
3 namespace jakobo\HOTP;
4
5 /**
6 * The HOTPResult Class converts an HOTP item to various forms
7 * Supported formats include hex, decimal, string, and HOTP
8
9 * @author Jakob Heuser (firstname)@felocity.com
10 * @copyright 2011-2020
11 * @license BSD-3-Clause
12 * @version 1.0
13 */
14 class HOTPResult {
15 protected $hash;
16 protected $decimal;
17 protected $hex;
18
19 /**
20 * Build an HOTP Result
21 * @param string $value the value to construct with
22 * @codeCoverageIgnore
23 */
24 public function __construct( string $value ) {
25 // store raw
26 $this->hash = $value;
27 }
28
29 /**
30 * Returns the string version of the HOTP
31 * @return string
32 */
33 public function toString(): string {
34 return $this->hash;
35 }
36
37 /**
38 * Returns the hex version of the HOTP
39 * @return string
40 */
41 public function toHex(): string {
42 if( !$this->hex ) {
43 $this->hex = dechex( $this->toDec() );
44 }
45 return $this->hex;
46 }
47
48 /**
49 * Returns the decimal version of the HOTP
50 * @return int
51 */
52 public function toDec(): int {
53 if( !$this->decimal ) {
54 // store calculate decimal
55 $hmac_result = [];
56
57 // Convert to decimal
58 foreach ( str_split( $this->hash,2 ) as $hex ) {
59 $hmac_result[] = hexdec($hex);
60 }
61
62 $offset = $hmac_result[19] & 0xf;
63
64 $this->decimal = (
65 ( ( $hmac_result[$offset+0] & 0x7f ) << 24 ) |
66 ( ( $hmac_result[$offset+1] & 0xff ) << 16 ) |
67 ( ( $hmac_result[$offset+2] & 0xff ) << 8 ) |
68 ( $hmac_result[$offset+3] & 0xff )
69 );
70 }
71 return $this->decimal;
72 }
73
74 /**
75 * Returns the truncated decimal form of the HOTP
76 * @param int $length the length of the HOTP to return
77 * @return string
78 */
79 public function toHOTP( int $length ): string {
80 $str = str_pad( $this->toDec(), $length, "0", STR_PAD_LEFT );
81 return substr( $str, ( -1 * $length ) );
82 }
83
84 }