Add safety with nulls

This commit is contained in:
2024-09-11 23:13:43 +02:00
parent 68cb002951
commit a0ffa2f682
7 changed files with 150 additions and 53 deletions
+17 -7
View File
@@ -11,21 +11,31 @@ export default class PwdBox {
private readonly salt: Uint8Array
) {}
private static async derive(pwd: string, salt: Uint8Array, context?: string): Promise<CryptoKey> {
const k = await pbkdf(salt, pwd) // TODO : null
return await hkdf(k, Usage.box, context) as CryptoKey // TODO : null
private static async derive(pwd: string, salt: Uint8Array, context?: string): Promise<CryptoKey | null> {
const k = await pbkdf(salt, pwd)
if (k === null) return null
return await hkdf(k, Usage.box, context) as CryptoKey
}
public static async encrypt(data: Uint8Array, pwd: string, context?: string): Promise<PwdBox> {
public static async encrypt(data: Uint8Array, pwd: string, context?: string): Promise<PwdBox | null> {
log.trace('encrypt')
const salt = crypto.getRandomValues(new Uint8Array(16))
const k = await PwdBox.derive(pwd, salt, context) // TODO : null
const box = await SecretBox.encrypt(data, k) // TODO : null
const k = await PwdBox.derive(pwd, salt, context)
if (k === null) return null
const box = await SecretBox.encrypt(data, k)
if (box === null) return null
return new PwdBox(box, salt)
}
public async decrypt(pwd: string, context?: string): Promise<Uint8Array | null> {
log.trace('decrypt')
const k = await PwdBox.derive(pwd, this.salt, context) // TODO : null
const k = await PwdBox.derive(pwd, this.salt, context)
if (k === null) return null
return await this.box.decrypt(k)
}