All files / src/crypter/modeOfOperation OFBMode.ts

100% Statements 5/5
100% Branches 0/0
100% Functions 0/0
100% Lines 5/5

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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 631x   1x   1x   10x   10x                                                                                                            
import randomBytes from 'randombytes';
import type { IModeOfOperation, IDecryptionModeOfOperation, IEncryptionModeOfOperation } from './IModeOfOperation';
import { xor } from '../../utils/xor';
 
export class OFBMode implements IModeOfOperation {
 
    public readonly encryption = new OFBMode.OFBEncryptionMode();
 
    public readonly decryption = new OFBMode.ECBDecryptionMode();
}
 
// istanbul ignore next
export namespace OFBMode {
 
    export class OFBEncryptionMode implements IEncryptionModeOfOperation {
 
        private initializationVector: Uint8Array | null = null;
 
        public start(): Uint8Array {
            this.initializationVector = randomBytes(16);
            return this.initializationVector;
        }
 
        public combine(block: Uint8Array, encrypt: (block: Uint8Array) => Uint8Array): Uint8Array {
            if (this.initializationVector === null)
                throw new Error('OFB encryption mode not started.');
            const encrypted = xor(this.initializationVector, encrypt(block));
            this.initializationVector = encrypted;
            return encrypted;
        }
 
        public finish(): Uint8Array {
            this.initializationVector = null;
            return new Uint8Array();
        }
    }
 
    export class ECBDecryptionMode implements IDecryptionModeOfOperation {
 
        private initializationVector: Uint8Array | null = null;
 
        public start(): Uint8Array {
            this.initializationVector = null;
            return new Uint8Array();
        }
 
        public combine(block: Uint8Array, decrypt: (block: Uint8Array) => Uint8Array): Uint8Array {
            if (this.initializationVector === null) {
                this.initializationVector = block;
                return new Uint8Array();
            }
            const decrypted = decrypt(xor(this.initializationVector, block));
            this.initializationVector = block;
            return decrypted;
        }
 
        public finish(): Uint8Array {
            this.initializationVector = null;
            return new Uint8Array();
        }
    }
}