Search code examples
javascriptnode.jscryptographycryptojspbkdf2

pbkdf2 returns a hash with 128 characters instead of 64


I want to create password hashes when creating users and store them to my database. My database password column stores hashes of 64 chars (nvarchar(64)). My hash configuration:

const byteAmount: number = Number(process.env.BYTE_AMOUNT) || 16;
const iterations: number = Number(process.env.ITERATIONS) || 100;
const length: number = Number(process.env.LENGTH) || 64;
const algorithm: string = process.env.ALGORITHM || 'sha512';
const conversion: string = process.env.CONVERSION || 'Hex';

When hashing the users plain text password I use this function

public hashPassword = (password: BinaryLike, passwordSalt: BinaryLike): string => {
    const { iterations, length, algorithm }: { iterations: number, length: number, algorithm: string } = passwordConfig;
    const passwordHash: string = pbkdf2Sync(password, passwordSalt, iterations, length, algorithm).toString(passwordConfig.conversion);
    return passwordHash;
}

Unfortunately the hash function returns a password hash with 128 characters. Is it possible to define a hash length or do I always get returned a 128 characters long hash?


Solution

  • Parameter keylen (length in your snippet) specifies number of bytes in the returned buffer. Converting this buffer to a hex string doubles the returned string, because each byte is represented by two characters.

    If you want to get a hex string of 64 chars, then you must set length = 32.