import { Constants, KeyStatus, KeyType, KeyUsage } from './common/Constants' import * as crypto from 'crypto' import { KeyEncryption } from './common/KeyEncryption' export class Mkey { service_identifier: string id: Buffer ver: number key: Buffer key_usage: KeyUsage key_status: KeyStatus key_type: KeyType is_valid: boolean expired: number effective: number s_key: Buffer key_digest: string constructor( service: string, kid: Buffer, key: Buffer, k_digest: string, k_ver: number, effective_ts: number, exp_ls: number, k_type: string, k_usage: string, k_status: number ) { if (!service || !kid) { throw new Error(`ID and App fields cannot be null.`) } this.service_identifier = service this.id = kid this.ver = k_ver if (k_ver < -1) { throw new Error(`Invalid key version.`) } this.key_usage = Constants.KeyUsages.from_value(k_usage) this.key_status = Constants.KeyStatuses.from_value(k_status) this.key_type = Constants.KeyTypes.from_value(k_type) this.is_valid = false if (key) { this.key = key this.expired = exp_ls this.effective = effective_ts this.s_key = key.subarray(0, 16) } this.key_digest = k_digest // py3: digest = base64_util.encode_to_string(sha256(key).digest()) const digest = crypto.createHash('sha256').update(key).digest().toString('base64') if (digest === k_digest) { this.is_valid = true } } decrypt(ct: Buffer) { if (ct[0] != Constants.CipherTypes.Weak.id) { throw new Error(`Unmatch CipherText Type.`) } if (ct[1] != Constants.AlgoTypes.AesCbc128.id) { throw new Error(`Unmatch Encryption Algorithm Type: ${ct[1]}`) } if (ct.subarray(2, 2 + this.id.length).toString() !== this.id.toString()) { throw new Error(`Unmatch MKey ID.`) } return KeyEncryption.aes_decrypt(this, ct.subarray(2 + this.id.length)) } }