Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace bcrypt with crypto #113

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,11 @@
"author": "",
"license": "BSD",
"optionalDependencies": {
"bcrypt": "^5.1.1",
"bcryptjs": "^2.4.3",
"sha.js": "^2.4.11"
},
"devDependencies": {
"@balena/abstract-sql-compiler": "^9.2.0",
"@balena/lint": "^8.2.7",
"@types/bcrypt": "^5.0.2",
"@types/chai": "^4.3.16",
"@types/chai-datetime": "^0.0.39",
"@types/mocha": "^10.0.6",
Expand Down
40 changes: 25 additions & 15 deletions src/types/hashed.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,6 @@
import type * as Bcrypt from 'bcrypt';

import * as crypto from 'crypto';
import * as TypeUtils from '../type-utils';

let bcrypt: typeof Bcrypt;
try {
bcrypt = require('bcrypt');
} catch {
bcrypt = require('bcryptjs');
}

export const types = {
postgres: 'CHAR(60)',
mysql: 'CHAR(60)',
Expand All @@ -26,11 +18,29 @@ export const validate: TypeUtils.Validate<Types['Write'], DbWriteType> =
if (typeof value !== 'string') {
throw new Error('is not a string');
}
const salt = await bcrypt.genSalt();
return bcrypt.hash(value, salt);
const salt = crypto.randomBytes(16).toString('hex');
return new Promise((resolve, reject) => {
crypto.pbkdf2(value, salt, 1000, 64, 'sha512', (err, derivedKey) => {
Comment on lines +21 to +22
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about trying https://www.npmjs.com/package/@node-rs/bcrypt so that we don't need to do this breaking change?

if (err) {
reject(err);
}
resolve(derivedKey.toString('hex'));
});
});
});

export const compare: (
data: string | Buffer,
encrypted: string,
) => Promise<boolean> = bcrypt.compare.bind(bcrypt);
export const compare = (data: string | Buffer, encrypted: string) => {
return new Promise<boolean>((resolve, reject) => {
const [storedHash, storedSalt] = encrypted.split('$');
if (!storedSalt) {
reject(new Error('Invalid hash'));
return;
}
crypto.pbkdf2(data, storedSalt, 1000, 64, 'sha512', (err, derivedKey) => {
if (err) {
return reject(err);
}
resolve(storedHash === derivedKey.toString('hex'));
});
});
};
Loading