diff --git a/src/secret-wrap.ts b/src/secret-wrap.ts index ca3f423..38e530b 100644 --- a/src/secret-wrap.ts +++ b/src/secret-wrap.ts @@ -71,11 +71,28 @@ export class SecretWrap { type: this.type }) } - public static fromString(data: string): SecretWrap { + public static fromString(data: string): SecretWrap | null { log.trace('fromString') - const obj = JSON.parse(data) - const cipher = b642a(obj.cipher).expect('Failed to decode cipher') - const iv = b642a(obj.iv).expect('Failed to decode IV') - return new SecretWrap(cipher, obj.algorithm, obj.usages, obj.type, iv) + + const obj = this.parseJSON(data) + if (obj === null) return null + + const cipher = b642a(obj.cipher) + if (cipher.is_err()) return null + const iv = b642a(obj.iv) + if (iv.is_err()) return null + + return new SecretWrap(cipher.unwrap(), obj.algorithm, obj.usages, obj.type, iv.unwrap()) + } + + private static parseJSON(data: string): {cipher: string, iv: string, algorithm: KeyAlgorithm, usages: KeyUsage[], type: 'raw' | 'pkcs8'} | null { + log.trace('parseJSON') + try { + // TODO : Check the fields + return JSON.parse(data) + } catch (e) { + log.warn('Failed to parse JSON') + return null + } } }