&sig=. * Signing the exact base64 text avoids canonicalisation bugs, and nothing secret is in the URL. * * @package AccessNow\Replica */ namespace AccessNow\Replica\Crypto; use AccessNow\Replica\Secrets; defined( 'ABSPATH' ) || exit; /** * Key derivation and envelope signing. */ final class Signer { const DOMAIN = "SITE-REPLICA-REQ-V1\n"; /** * Signing key. * * @param string $secret Raw 32-byte secret. */ public static function sign_key( $secret ) { return hash_hmac( 'sha256', 'site-replica/v1/sign', $secret, true ); } /** * Response encryption key. * * @param string $secret Raw 32-byte secret. */ public static function enc_key( $secret ) { return hash_hmac( 'sha256', 'site-replica/v1/enc', $secret, true ); } /** * Builds a signed request body. * * @param string $secret Raw secret. * @param string $kid Key ID. * @param string $op Operation. * @param array $args Arguments. * @param array $budget Budget hints {ms, bytes}. * @param int $clock_offset Seconds to add to local time (server skew). * @return array{body: array, nonce: string} */ public static function envelope( $secret, $kid, $op, array $args, array $budget, $clock_offset = 0 ) { $nonce = Secrets::b64url_encode( random_bytes( 16 ) ); $env = Secrets::b64url_encode( (string) wp_json_encode( array( 'v' => ACCESSNOW_REPLICA_PROTOCOL, 'kid' => $kid, 'ts' => time() + (int) $clock_offset, 'nonce' => $nonce, 'op' => $op, 'args' => (object) $args, 'budget' => $budget, ), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) ); return array( 'body' => array( 'env' => $env, 'sig' => hash_hmac( 'sha256', self::DOMAIN . $env, self::sign_key( $secret ) ), ), 'nonce' => $nonce, ); } /** * Checks a signature in constant time. * * @param string $secret Raw secret. * @param string $env Envelope text as received. * @param string $sig Hex signature as received. */ public static function verify( $secret, $env, $sig ) { if ( ! is_string( $sig ) || ! preg_match( '/^[a-f0-9]{64}$/', $sig ) ) { return false; } return hash_equals( hash_hmac( 'sha256', self::DOMAIN . $env, self::sign_key( $secret ) ), $sig ); } }