# patchstack/2.1.4/includes/2fa/rfc6238.php

Patchstack – WordPress &amp; Plugins Security, version 2.1.4. 94 lines.

- Page: https://pluginprobe.com/plugins/patchstack/2.1.4/code/includes/2fa/rfc6238.php
- Raw: https://pluginprobe.com/plugins/patchstack/2.1.4/raw/includes/2fa/rfc6238.php
- Modified: 2021-11-01T08:59:56+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/patchstack/2.1.4/code/includes/2fa/rfc6238.php#L10-L20`.

```php
<?php

// Do not allow the file to be called directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

require_once dirname( __FILE__ ) . '/base32.php';

class TokenAuth6238 {

	/**
	 * Verify the code & token.
	 *
	 * @param string $secretkey Secret clue (base 32).
	 * @return bool True if success, false if failure
	 */
	public static function verify( $secretkey, $code, $rangein30s = 3 ) {
		$key           = base32static::decode( $secretkey );
		$unixtimestamp = time() / 30;

		for ( $i = -( $rangein30s ); $i <= $rangein30s; $i++ ) {
			$checktime = (int) ( $unixtimestamp + $i );
			$thiskey   = self::oath_hotp( $key, $checktime );

			if ( (int) $code == self::oath_truncate( $thiskey, 6 ) ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Generate the random clue/key.
	 *
	 * @param integer $length
	 * @return string
	 */
	public static function generateRandomClue( $length = 16 ) {
		$b32 = '234567QWERTYUIOPASDFGHJKLZXCVBNM';
		$s   = '';
		for ( $i = 0; $i < $length; $i++ ) {
			$s .= $b32[ mt_rand( 0, 31 ) ];
		}

		return $s;
	}

	/**
	 *
	 * @param string  $key
	 * @param integer $counter
	 * @return string
	 */
	private static function oath_hotp( $key, $counter ) {
		$cur_counter = array( 0, 0, 0, 0, 0, 0, 0, 0 );

		for ( $i = 7; $i >= 0; $i-- ) { // C for unsigned char, * for  repeating to the end of the input data
			$cur_counter[ $i ] = pack( 'C*', $counter );
			$counter           = $counter >> 8;
		}

		$binary = implode( $cur_counter );

		// Pad to 8 characters
		str_pad( $binary, 8, chr( 0 ), STR_PAD_LEFT );
		return hash_hmac( 'sha1', $binary, $key );
	}

	/**
	 * Truncate
	 *
	 * @param string  $hash
	 * @param integer $length
	 * @return boolean
	 */
	private static function oath_truncate( $hash, $length = 6 ) {
		$hashcharacters = str_split( $hash, 2 );

		for ( $j = 0; $j < count( $hashcharacters ); $j++ ) {
			$hmac_result[] = hexdec( $hashcharacters[ $j ] );
		}

		$offset = $hmac_result[19] & 0xf;
		return (
				( ( $hmac_result[ $offset + 0 ] & 0x7f ) << 24 ) |
				( ( $hmac_result[ $offset + 1 ] & 0xff ) << 16 ) |
				( ( $hmac_result[ $offset + 2 ] & 0xff ) << 8 ) |
				( $hmac_result[ $offset + 3 ] & 0xff )
		) % pow( 10, $length );
	}
}

```
