Projekt

Obecné

Profil

Stáhnout (1.16 KB) Statistiky
| Větev: | Revize:
1
var Buffer = require('safe-buffer').Buffer
2
var MD5 = require('md5.js')
3

    
4
/* eslint-disable camelcase */
5
function EVP_BytesToKey (password, salt, keyBits, ivLen) {
6
  if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')
7
  if (salt) {
8
    if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')
9
    if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')
10
  }
11

    
12
  var keyLen = keyBits / 8
13
  var key = Buffer.alloc(keyLen)
14
  var iv = Buffer.alloc(ivLen || 0)
15
  var tmp = Buffer.alloc(0)
16

    
17
  while (keyLen > 0 || ivLen > 0) {
18
    var hash = new MD5()
19
    hash.update(tmp)
20
    hash.update(password)
21
    if (salt) hash.update(salt)
22
    tmp = hash.digest()
23

    
24
    var used = 0
25

    
26
    if (keyLen > 0) {
27
      var keyStart = key.length - keyLen
28
      used = Math.min(keyLen, tmp.length)
29
      tmp.copy(key, keyStart, 0, used)
30
      keyLen -= used
31
    }
32

    
33
    if (used < tmp.length && ivLen > 0) {
34
      var ivStart = iv.length - ivLen
35
      var length = Math.min(ivLen, tmp.length - used)
36
      tmp.copy(iv, ivStart, used, used + length)
37
      ivLen -= length
38
    }
39
  }
40

    
41
  tmp.fill(0)
42
  return { key: key, iv: iv }
43
}
44

    
45
module.exports = EVP_BytesToKey
(3-3/4)