-
Notifications
You must be signed in to change notification settings - Fork 576
/
evp_bytes_to_key.ts
54 lines (45 loc) · 1.43 KB
/
evp_bytes_to_key.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
50
51
52
53
54
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 crypto-browserify. All rights reserved. MIT license.
import { Buffer } from "../../buffer.ts";
import { createHash } from "../../internal/crypto/hash.ts";
export function EVP_BytesToKey(
password: string | Buffer,
salt: string | Buffer,
keyBits: number,
ivLen: number,
) {
if (!Buffer.isBuffer(password)) password = Buffer.from(password, "binary");
if (salt) {
if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, "binary");
if (salt.length !== 8) {
throw new RangeError("salt should be Buffer with 8 byte length");
}
}
let keyLen = keyBits / 8;
const key = Buffer.alloc(keyLen);
const iv = Buffer.alloc(ivLen || 0);
let tmp = Buffer.alloc(0);
while (keyLen > 0 || ivLen > 0) {
const hash = createHash("md5");
hash.update(tmp);
hash.update(password);
if (salt) hash.update(salt);
tmp = hash.digest() as Buffer;
let used = 0;
if (keyLen > 0) {
const keyStart = key.length - keyLen;
used = Math.min(keyLen, tmp.length);
tmp.copy(key, keyStart, 0, used);
keyLen -= used;
}
if (used < tmp.length && ivLen > 0) {
const ivStart = iv.length - ivLen;
const length = Math.min(ivLen, tmp.length - used);
tmp.copy(iv, ivStart, used, used + length);
ivLen -= length;
}
}
tmp.fill(0);
return { key, iv };
}
export default EVP_BytesToKey;