1
resposta

Dúvida sobre Buffer

Olá, não entendi direito o porquê de na função "autentica" foi utilizado Buffer.from(this.hash, 'hex'); ao invés de simplesmente o this.hash, que, em teoria, já era pra ter o valor do hash a ser comparado?

1 resposta

A função timingSafeEqual utilizada para comparar a hash 'real' com a hash 'de teste' aceita dois parâmetros, e ambos devem ser de algum dos seguintes tipos: ArrayBuffer ,Buffer, TypedArray, ouDataView. O importante, é que os dois argumentos sejam do mesmo tipo, e tenham o mesmo "comprimento" em bytes.

O valor de this.hash é do tipo String, enquanto o valor de testeHash é um Buffer. Logo, é necessário converter this.hash para um Buffer para que se possa fazer a comparação segura das duas hashes. E para isso, o método Buffer.from é utilizado.

Se não captou a ideia por trás dos Buffers, recomendo que veja o seguinte artigo: Using Buffers In Node.js, e que dê uma espiada na documentação: Node.js API - Buffers

De acordo com a documentação oficial:

(Node.js v19.0.0)

Crypto.timingSafeEqual(a, b)

a : ArrayBuffer | Buffer | TypedArray | DataView

b : ArrayBuffer | Buffer | TypedArray | DataView

Returns: Boolean

This function compares the underlying bytes that represent the given ArrayBuffer, TypedArray, or DataView instances using a constant-time algorithm. This function does not leak timing information that would allow an attacker to guess one of the values. This is suitable for comparing HMAC digests or secret values like authentication cookies or capability urls. a and b must both be Buffers, TypedArrays, or DataViews, and they must have the same byte length. An error is thrown if a and b have different byte lengths.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software