79 - ChatOS - Generate encryption key with PBKDF2

Livestream

Yesterday I added TweetNaCl.js to encrypt chat messages, by the way it needs a 32-byte encryption key, it is strong but long and hard to memorize.

Using PBKDF2 will enable user to use their own passphrase and generate longer keys, I’ll use @noble/hashes package since it’s quite popular and have TypeScript support built-in.

The usage is simple:

import { pbkdf2Async } from '@noble/hashes/pbkdf2';
import { sha256 } from '@noble/hashes/sha256';
import { encodeBase64 } from 'tweetnacl-util'; // TweetNaCl needs base64 formatted key

const key = encodeBase64(
    await pbkdf2Async(sha256, "passphrase", 'some-salt', { 
        c: 300000, // No. of iterations
        dkLen: 32, // Length of key
    })
);

localStorage.setItem('encryption-key', key);

PBKDF2 References