How to use the PBKDF2 function from crypto-js

Find comprehensive JavaScript crypto-js.PBKDF2 code examples handpicked from public code repositorys.

crypto-js.PBKDF2 is a function that applies the Password-Based Key Derivation Function 2 (PBKDF2) algorithm to derive a derived key from a password and a salt.

242
243
244
245
246
247
248
249
250
251

function pbkdf2Encrypt() {
    var text = "I love Python!"
    var salt = "43215678"
    // key 长度 128,10 次重复运算
    var encryptedData = CryptoJS.PBKDF2(text, salt, {keySize: 128/32,iterations: 10});
    return encryptedData.toString()
}

console.log(pbkdf2Encrypt())  // 7fee6e8350cfe96314c76aaa6e853a50
fork icon34
star icon57
watch icon0

+ 7 other calls in file

91
92
93
94
95
96
97
98
99
100
 */
type Pbkdf2Options = {salt:string, size:number, iterations:number}
export async function pbkdf2(masterKey: string, options?: Partial<Pbkdf2Options>) : Promise<{key:string, salt: string}>{
  const salt = CryptoJS.enc.Hex.parse(options?.salt || await randomBytesHexString(8))
  const iterations = options?.iterations || 1
  const key = CryptoJS.PBKDF2(masterKey,salt,{
    keySize: options?.size || 4, 
    iterations
  }).toString()
  return {key, salt: salt.toString()}
fork icon0
star icon2
watch icon1

+ 2 other calls in file

How does crypto-js.PBKDF2 work?

crypto-js.PBKDF2 is a function in the CryptoJS library that implements the Password-Based Key Derivation Function 2 (PBKDF2) algorithm, which takes a password and a salt and produces a derived key by iterating a pseudorandom function a configurable number of times. The output key can be used as a cryptographic key or password hash. The function takes parameters such as the password, salt, number of iterations, and desired key size.

213
214
215
216
217
218
219
220
221
222
If you disabled the new user signup as suggested at the end of the first part of the tutorial then you'll have a slightly harder time creating a new user (the Signup page is still enabled in the example repo for convenience). You could create one with the Redwood console, but you'll need to be clever—remember that we don't store the original password, just the hashed result when combined with a salt. Here's the commands to enter at the console for creating a new user (replace 'password' with your password of choice):

```javascript
const CryptoJS = require('crypto-js')
const salt = CryptoJS.lib.WordArray.random(128 / 8).toString()
const hashedPassword = CryptoJS.PBKDF2('password', salt, { keySize: 256 / 32 }).toString()
db.user.create({ data: { email: 'moderator@moderator.com', hashedPassword, salt } })
```

:::
fork icon882
star icon0
watch icon0

1
2
3
4
5
6
7
8
9
10
const Keystore = require('./keystore');

const HD_PATH_STRING = 'm/0\'/0\'/0\'';

function legacyGenerateEncKey(password, salt) {
  return CryptoJS.PBKDF2(password, salt, {
    keySize: 512 / 32,
    iterations: 150,
  }).toString();
}
fork icon486
star icon0
watch icon77

Ai Example

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

const password = "myPassword123"; // the password to derive the key from
const salt = "1234"; // a salt value to make the key unique
const iterations = 1000; // the number of iterations to perform

const key = CryptoJS.PBKDF2(password, salt, {
  keySize: 256 / 32, // the desired key size in bits
  iterations: iterations, // the number of iterations to perform
});

console.log(key.toString(CryptoJS.enc.Hex)); // logs the derived key as a hex string

In this example, we're using CryptoJS to derive a key from a password using the PBKDF2 algorithm. We provide the password, a salt value, and the iterations to use. We also specify the desired keySize in bits. Finally, we log the derived key as a hex string.

33
34
35
36
37
38
39
40
41
42
public static toMobileKey = (password, privateKey) => {
    // Errors
    if (!password || !privateKey) { throw new Error('Missing argument !'); }
    // Processing
    const salt = CryptoJS.lib.WordArray.random(256 / 8);
    const key = CryptoJS.PBKDF2(password, salt, {
        keySize: 256 / 32,
        iterations: 2000,
    });
    const iv = Crypto.randomBytes(16);
fork icon61
star icon0
watch icon2

24
25
26
27
28
29
30
31
32
33

    return bytes.toString(CryptoJS.enc.Utf8);
}

public static PBKDF2(password: string, keySize: number): string { //for generate private key
    return CryptoJS.PBKDF2(
        password,
        CryptoUtils.sha384(CryptoUtils.sha384(password)),
        {keySize: keySize / 32, iterations: 10000}
    ).toString(CryptoJS.enc.Hex);
fork icon11
star icon0
watch icon2

184
185
186
187
188
189
190
191
192
193
* Author: flohall
* date: 2019-11-05
* file: module/textEncryptor.js
* Original: <https://stackoverflow.com/a/58720652/151048>.
*/
const key = CryptoJS.PBKDF2(ENCRYPTION_PASSWORD, ENCRYPTION_SALT, {
	keySize: 256 / 32,
	iterations: 1024
});

fork icon0
star icon0
watch icon1

+ 4 other calls in file

4
5
6
7
8
9
10
11
12
const iterations = 100;

module.exports = {
    encrypt(data, encryptionPassword) {
        var salt = CryptoJS.lib.WordArray.random(128 / 8);
        var key = CryptoJS.PBKDF2(encryptionPassword, salt, {
            keySize: keySize / 32,
            iterations: iterations
        });
fork icon0
star icon0
watch icon4

+ 3 other calls in file

7
8
9
10
11
12
13
14
15
16
  this.keySize = keySize / 32;
  this.iterationCount = iterationCount;
};

AesUtil.prototype.generateKey = function(salt, passPhrase) {
  var key = CryptoJS.PBKDF2(passPhrase, CryptoJS.enc.Hex.parse(salt), {
      keySize: this.keySize,
      iterations: this.iterationCount
  });
  return key;
fork icon0
star icon0
watch icon1