-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
aes-ctr.ts
49 lines (41 loc) · 1.19 KB
/
aes-ctr.ts
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
41
42
43
44
45
46
47
48
49
import { arrayify } from '@ethersproject/bytes';
import { pbkdf2 } from '@ethersproject/pbkdf2';
import { strategy } from './universal-crypto';
export interface Keystore {
data: string;
iv: string;
salt: string;
}
export function bufferFromString(
string: string,
encoding: 'utf-8' | 'base64' = 'base64'
): Uint8Array {
if (strategy === 'Node') {
return Buffer.from(string, encoding);
}
if (encoding === 'utf-8') {
return new TextEncoder().encode(string);
}
return new Uint8Array(
atob(string)
.split('')
.map((c) => c.charCodeAt(0))
);
}
export function stringFromBuffer(
buffer: Uint8Array,
encoding: 'utf-8' | 'base64' = 'base64'
): string {
if (strategy === 'Node') {
return Buffer.from(buffer).toString(encoding);
}
return btoa(String.fromCharCode.apply(null, new Uint8Array(buffer) as unknown as number[]));
}
/**
* Generate a pbkdf2 key from a password and random salt
*/
export function keyFromPassword(password: string, saltBuffer: Uint8Array): Uint8Array {
const passBuffer = bufferFromString(String(password).normalize('NFKC'), 'utf-8');
const key = pbkdf2(passBuffer, saltBuffer, 100000, 32, 'sha256');
return arrayify(key);
}