All files / utils stringCoding.ts

87.5% Statements 14/16
66.66% Branches 4/6
50% Functions 1/2
87.5% Lines 14/16

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 351x   1x       4x       4x 4x 4x     4x 1x     3x 3x   3x 3x   3x     1x            
import { createHash } from 'crypto';
 
export function deriveStringToBuffer(
    ss: string | undefined,
    targetLength: number
): Buffer {
    Iif (!ss) {
        return Buffer.alloc(targetLength);
    }
 
    let base64Buffer: Buffer | null = null;
    try {
        base64Buffer = Buffer.from(ss, 'base64');
    } catch { }
 
    if (base64Buffer?.length === targetLength) {
        return base64Buffer;
    }
 
    const inputBuffer = Buffer.from(ss, 'utf8');
    const hash = createHash('sha256').update(inputBuffer).digest();
 
    const outputBuffer = Buffer.alloc(targetLength);
    hash.copy(outputBuffer, 0, 0, targetLength);
 
    return outputBuffer;
}
 
export function deriveStringToUint8Array(
    ss: string | undefined,
    targetLength: number
): Uint8Array {
    return new Uint8Array(deriveStringToBuffer(ss, targetLength));
}