forked from utily/cryptly
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPassword.ts
More file actions
40 lines (39 loc) · 1.11 KB
/
Password.ts
File metadata and controls
40 lines (39 loc) · 1.11 KB
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
import * as Base64 from "./Base64"
import { crypto } from "./crypto"
export type Password = string | Password.Hash
export namespace Password {
export function is(value: any | Password): value is Password {
return (
typeof value == "string" ||
(typeof value == "object" && typeof value.hash == "string" && typeof value.salt == "string")
)
}
export async function hash(
algorithm: { sign: (data: string) => Promise<string> },
password: string,
salt?: string
): Promise<Hash> {
if (!salt)
salt = Base64.encode(crypto.getRandomValues(new Uint8Array(64)))
return {
hash: await algorithm.sign(salt + password),
salt,
}
}
export async function verify(
algorithm: { sign: (data: string) => Promise<string> },
hash: Hash,
password: string
): Promise<boolean> {
return (await Password.hash(algorithm, password, hash.salt)).hash == hash.hash
}
export interface Hash {
hash: string
salt: string
}
export namespace Hashed {
export function is(value: any | Hash): value is Hash {
return typeof value == "object" && typeof value.hash == "string" && typeof value.salt == "string"
}
}
}