Skip to content

Commit

Permalink
Fix: fix #26
Browse files Browse the repository at this point in the history
No response is still a response
  • Loading branch information
winderica committed Mar 28, 2021
1 parent 5745bf2 commit f3ec0ee
Showing 1 changed file with 3 additions and 26 deletions.
29 changes: 3 additions & 26 deletions packages/backend/src/utils/scrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,43 +6,20 @@ interface ScryptResult {
}

export const hash = (password: string) => new Promise<ScryptResult>((resolve, reject) => {
/*
* As the matter of fact, if `salt` is base64-encoded before it's passed to `scrypt`,
* `scrypt` will treat it as a (UTF-8) string and convert it to a buffer whose length is longer than 16.
* It works, although not as intended.
* The correct implementation is:
* ```js
* // hash
* const salt = randomBytes(16);
* scrypt(password, salt, 64, (err, derivedKey) => {
* // ...
* return resolve({
* salt: salt.toString('base64');
* hash: derivedKey.toString('base64'),
* });
* }
* // verify
* scrypt(password, Buffer.from(salt, 'base64'), 64, (err, derivedKey) => {
* // ...
* }
* ```
* For backward compatibility, we have to adapt to the mistake.
*/
const salt = randomBytes(16).toString('base64');

const salt = randomBytes(16);
scrypt(password, salt, 64, (err, derivedKey) => {
if (err) {
return reject(err);
}
return resolve({
salt,
salt: salt.toString('base64'),
hash: derivedKey.toString('base64'),
});
});
});

export const verify = (hash: string, salt: string, password: string) => new Promise<boolean>((resolve, reject) => {
scrypt(password, salt, 64, (err, derivedKey) => {
scrypt(password, Buffer.from(salt, 'base64'), 64, (err, derivedKey) => {
if (err) {
return reject(err);
}
Expand Down

0 comments on commit f3ec0ee

Please sign in to comment.