All files / lib Crypto.ts

85% Statements 34/40
78.57% Branches 11/14
100% Functions 3/3
85% Lines 34/40

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 401x 1x 1x 1x 7x 7x 7x 7x 7x 1x 1x 2x 2x 2x 2x       2x 2x 2x 2x 1x 1x 5x 5x 4x 5x 4x 4x       4x 4x 5x 5x 1x 1x 1x
import NodeCrypto from 'crypto';
 
class Crypto {
    static generateUUid(strength: number, date: boolean = true): string {
        let randString = "";
        if (date) randString += Date.now().toString();
        randString += NodeCrypto.randomBytes(strength).toString('hex');
        return randString.toLowerCase();
    }
 
    static generateTokenHash(password: string): Promise<string> {
        return new Promise((resolve, reject) => {
            const salt = NodeCrypto.randomBytes(16).toString('hex');
            NodeCrypto.pbkdf2(password, salt, 100000, 64, 'sha512', (err, hash) => {
                if (err) {
                    // TODO: Log error
                    return reject(err);
                }
                resolve(`${salt}:${hash.toString('hex')}`);
            });
        });
    }
 
    static verifyTokenHash(password: string, stored: string | false): Promise<boolean> {
        return new Promise((resolve, reject) => {
            if (!stored) return resolve(false);
            const [salt, originalHash] = stored.split(':');
            if (!salt || !originalHash) return resolve(false);
            NodeCrypto.pbkdf2(password, salt, 100000, 64, 'sha512', (err, hash) => {
                if (err) {
                    // TODO: Log error
                    return reject(err);
                }
                resolve(hash.toString('hex') === originalHash);
            });
        });
    }
}
 
export default Crypto;