Add PwdWrap
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
export {PrivateBox} from './asymmetric'
|
||||
export {SecretBox} from './symmetric'
|
||||
export {PwdBox} from './pwd'
|
||||
|
||||
export {PrivateWrap} from './private-wrap'
|
||||
export {SecretWrap} from './secret-wrap'
|
||||
export {PwdWrap} from './pwd-wrap'
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import {Result} from 'result'
|
||||
import * as misc from 'misc'
|
||||
import {SecretWrap} from './secret-wrap'
|
||||
import {pbkdf} from '../pbkdf'
|
||||
|
||||
export class PwdWrap {
|
||||
private constructor(
|
||||
private readonly secret_wrap: SecretWrap,
|
||||
private readonly salt: Uint8Array,
|
||||
) {}
|
||||
|
||||
public static async wrap(pwd: string, key_to_wrap: CryptoKey) : Promise<Result<PwdWrap>> {
|
||||
const salt = crypto.getRandomValues(new Uint8Array(18))
|
||||
const key = await PwdWrap.get_key(pwd, salt)
|
||||
|
||||
const box = await SecretWrap.wrap_key(key, key_to_wrap)
|
||||
if (box.error()) return Result.error([])
|
||||
|
||||
return Result.ok(new PwdWrap(box.unwrap(), salt))
|
||||
}
|
||||
|
||||
public async unwrap(pwd: string) : Promise<Result<CryptoKey>> {
|
||||
const key = await PwdWrap.get_key(pwd, this.salt)
|
||||
|
||||
const unwrapped_key = await this.secret_wrap.unwrap(key)
|
||||
if (unwrapped_key.error()) return Result.error([])
|
||||
|
||||
return Result.ok(unwrapped_key.unwrap())
|
||||
}
|
||||
|
||||
private static async get_key(pwd: string, salt: Uint8Array) : Promise<CryptoKey> {
|
||||
return pbkdf(pwd, salt, ['wrapKey', 'unwrapKey'])
|
||||
}
|
||||
|
||||
public toString() : string {
|
||||
const salt = misc.a2b64(this.salt)
|
||||
const box = this.secret_wrap.toString()
|
||||
return `${salt}${box}`
|
||||
}
|
||||
public static fromString(data: string) : Result<PwdWrap> {
|
||||
const salt64 = data.slice(0, 24)
|
||||
const salt = misc.b642a(salt64)
|
||||
if (salt.error()) return Result.error([])
|
||||
|
||||
const box64 = data.slice(24)
|
||||
const box = SecretWrap.fromString(box64)
|
||||
if (box.error()) return Result.error([])
|
||||
|
||||
return Result.ok(new PwdWrap(box.unwrap(), salt.unwrap()))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user