How to use the pbkdf2Sync function from crypto

Find comprehensive JavaScript crypto.pbkdf2Sync code examples handpicked from public code repositorys.

crypto.pbkdf2Sync is a synchronous version of the pbkdf2 function in Node.js's built-in crypto module that derives a cryptographic key from a password using a key derivation function.

18
19
20
21
22
23
24
25
26
27
    options = options || this.empty;
    const encode = options.encode === "binary" ? undefined : options.encode || "base64";
    key = Buffer.isBuffer(key) ? key : typeof key == "string" ? key : String(key);
    data = Buffer.isBuffer(data) ? data : Buffer.from(typeof data == "string" ? data : String(data));
    const iv = crypto.randomBytes(options.iv_length || 16);
    const password = crypto.pbkdf2Sync(key, iv.toString(), options.key_iterations || 10000, options.key_length || 32, options.key_hash || 'sha256');
    const cipher = crypto.createCipheriv(options.algorithm || 'aes-256-cbc', password, iv);
    var msg = Buffer.concat([iv, cipher.update(data), cipher.final()]);
    if (encode) msg = msg.toString(encode);
} catch (e) {
fork icon5
star icon40
watch icon9

+ 3 other calls in file

77
78
79
80
81
82
83
84
85
86
87
88
		done(null, results[0]);
	});
});


function validPassword(password, hash, salt) {
	const hashVerify = crypto.pbkdf2Sync(password, salt, 10000, 60, 'sha512').toString('hex');
	return hash === hashVerify;
}


function genPassword(password) {
fork icon1
star icon0
watch icon1

+ 3 other calls in file

How does crypto.pbkdf2Sync work?

crypto.pbkdf2Sync is a synchronous Node.js method used to derive a key of a specified length from the given password, salt, and iteration count using the Password-Based Key Derivation Function 2 (PBKDF2) algorithm, without any callbacks or Promises.

28
29
30
31
32
33
34
35
36
37
38
 * @param {String} hash - The hash stored in the database
 * @param {String} salt - The salt stored in the database
 * @return {Boolean} if password is correct
 */
function validPassword(password, hash, salt) {
    var hashVerify = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
    return hash === hashVerify;
}


/**
fork icon0
star icon0
watch icon1

684
685
686
687
688
689
690
691
692
693
694
695


//
// Test PBKDF2 with RFC 6070 test vectors (except #4)
//
function testPBKDF2(password, salt, iterations, keylen, expected) {
  const actual = crypto.pbkdf2Sync(password, salt, iterations, keylen,
                                   'sha256');
  assert.strictEqual(actual, expected);


  const cb = common.mustCall((err, actual) => {
fork icon0
star icon0
watch icon0

Ai Example

1
2
3
4
5
6
7
8
9
10
11
const crypto = require("crypto");

const password = "mysecretpassword";
const salt = "mysalt";
const iterations = 10000;
const keyLength = 64;
const digest = "sha512";

const hash = crypto.pbkdf2Sync(password, salt, iterations, keyLength, digest);

console.log(hash.toString("hex"));

In this example, we use crypto.pbkdf2Sync to generate a hash for the password 'mysecretpassword' with the salt 'mysalt', using 10000 iterations, a key length of 64, and the SHA-512 algorithm. The resulting hash is printed to the console as a hexadecimal string.

532
533
534
535
536
537
538
539
540
541
function createHashNSalt(userSecret){
	// Creating a unique salt 
    let salt = crypto.randomBytes(16).toString('hex');
  
    // Hashing user's salt and secret/password with 10,000 iterations, 64 length using sha512 digest
    let hash = crypto.pbkdf2Sync(userSecret, salt, 10000, 64, `sha512`).toString(`hex`);
	
	return [salt, hash];
}

fork icon0
star icon0
watch icon0

+ 3 other calls in file

10
11
12
13
14
15
16
17
18
19
class AuthService {
    hashPassword = async (password) => {
        return crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
    }
    verifyPassword = async (password, hashedPassword) => {
        const hash = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
        return hash === hashedPassword;
    }
    getIdAccount = async (role, id_auth) => {
        switch(role) {
fork icon0
star icon0
watch icon0

+ 3 other calls in file

11
12
13
14
15
16
17
18
19
20
21
22
  },
  { timestamps: true }
);


UserSchema.statics.validPassword = (password, salt, hash) => {    
    return hash === crypto.pbkdf2Sync(password, salt, 1000, 64, `sha512`).toString(`hex`); 
}


UserSchema.statics.setPassword = (password) => { 
  this.salt = crypto.randomBytes(16).toString('hex'); 
fork icon0
star icon0
watch icon0

+ 3 other calls in file

28
29
30
31
32
33
34
35
36
37
38
39


// Generate a Key based on openGauss jdbc driver (PBKDF2WithHmacSHA1)
// org.postgresql.util.MD5Digest.generateKFromPBKDF2
function generateKeyFromPBKDF2(password, random64code, server_iteration) {
    var random32code = Buffer.from(random64code,'hex');
    return crypto.pbkdf2Sync(password, random32code, server_iteration, 32, 'sha1');
}


// Deprecated function for convert buffer to hex string
// use buffer.toString('hex') instead
fork icon0
star icon0
watch icon0

20
21
22
23
24
25
26
27
28
29
30
function nativePBKDF2Sync (password, salt, iterations, keylen, digest) {
  checkParameters(iterations, keylen)
  password = toBuffer(password, defaultEncoding, 'Password')
  salt = toBuffer(salt, defaultEncoding, 'Salt')
  digest = digest || 'sha1'
  return native.pbkdf2Sync(password, salt, iterations, keylen, digest)
}


/* istanbul ignore next */
if (!native.pbkdf2Sync || native.pbkdf2Sync.toString().indexOf('keylen, digest') === -1) {
fork icon0
star icon0
watch icon0

5
6
7
8
9
10
11
12
13
14
15
16
17
const privateKey = fs.readFileSync(path.join(__dirname, '..', '/private_key.pem' ) , 'utf-8')




const genPasswd = (passwd)=>{
    const salt = crypto.randomBytes(64).toString('hex')
    const hash = crypto.pbkdf2Sync(passwd , salt, 10000,64,'sha256').toString('hex');
    return { hash , salt}
}


const verifypasswd = (passwd, hash ,salt)=>{
fork icon0
star icon0
watch icon0

191
192
193
194
195
196
197
198
199
200
  );
  Core.ensureTrue(count > 0 && keyLength > 0, "Invalid PBKDF2 parameters.");
  if (!rawOutput) {
    keyLength = keyLength * 2;
  }
  const hash = crypto.pbkdf2Sync(password, salt, count, keyLength, algorithm);
  return rawOutput ? hash : hash.toArray("hex");
}
static ord(string) {
  const str = string + "";
fork icon0
star icon0
watch icon0

+ 2 other calls in file