Skip to content

Commit 5879957

Browse files
authored
fix(bcrypt): hash should accept long or short string (#864)
1 parent dd71564 commit 5879957

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

packages/bcrypt/__tests__/bcrypt.spec.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
import test from 'ava'
22

3-
import { verifySync, compareSync, verify, compare, hash, genSaltSync, genSalt } from '../index'
3+
import {
4+
verifySync,
5+
compareSync,
6+
verify,
7+
compare,
8+
hash,
9+
genSaltSync,
10+
genSalt,
11+
hashSync as bcryptHashSync,
12+
} from '../index'
413

514
const { hashSync } = require('bcryptjs')
615

@@ -45,3 +54,8 @@ test('compare should be equal to verify', (t) => {
4554
t.is(verifySync, compareSync)
4655
t.is(verify, compare)
4756
})
57+
58+
test('hash should support long or short string', (t) => {
59+
t.is(typeof bcryptHashSync('string', 10, 'hello'), 'string')
60+
t.is(typeof bcryptHashSync('string', 10, 'aloooooooooooooooooooooongsalt'), 'string')
61+
})

packages/bcrypt/src/lib.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
/// Explicit extern crate to use allocator.
55
extern crate global_alloc;
66

7+
use std::cmp;
8+
79
use bcrypt::Version;
810
use napi::bindgen_prelude::*;
911
use napi::{Error, JsBuffer, Result, Status};
@@ -57,7 +59,9 @@ pub fn hash_sync(
5759
let salt = if let Some(salt) = salt {
5860
let mut s = [0u8; 16];
5961
let buf = either_string_buffer_as_bytes(&salt);
60-
s.copy_from_slice(&buf[..16]);
62+
// make sure salt buffer length should be 16
63+
let copy_length = cmp::min(buf.len(), s.len());
64+
s[..copy_length].copy_from_slice(&buf[..copy_length]);
6165
s
6266
} else {
6367
gen_salt().map_err(|err| Error::new(Status::InvalidArg, format!("{err}")))?
@@ -78,7 +82,9 @@ pub fn hash(
7882
let salt = if let Some(salt) = salt {
7983
let mut s = [0u8; 16];
8084
let buf = either_string_buffer_as_bytes(&salt);
81-
s.copy_from_slice(&buf[..16]);
85+
// make sure salt buffer length should be 16
86+
let copy_length = cmp::min(buf.len(), s.len());
87+
s[..copy_length].copy_from_slice(&buf[..copy_length]);
8288
s
8389
} else {
8490
gen_salt().map_err(|err| Error::new(Status::InvalidArg, format!("{err}")))?

0 commit comments

Comments
 (0)