Function: constantTimeEqual()
constantTimeEqual(
a,b):boolean
Compare two secrets (signatures, tokens, API keys) in a time that does not depend on their content or their lengths, so an attacker cannot guess a secret by timing the comparisons. Values of different lengths are compared too, and are unequal. Use it instead of === whenever one side is a secret; to check a password, use PasswordHash.validate instead.
Parameters
a
string | Uint8Array<ArrayBufferLike>
The first value: a string (compared as its UTF-8 bytes) or bytes.
b
string | Uint8Array<ArrayBufferLike>
The second value: a string (compared as its UTF-8 bytes) or bytes.
Returns
boolean
true when both values hold the same bytes.
Example
typescript
import {constantTimeEqual} from 'lakutata/security'
declare const presentedApiKey: string
if (!constantTimeEqual(presentedApiKey, process.env.API_KEY ?? '')) throw new Error('Unauthorized')