This repository was archived by the owner on May 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
103 lines (88 loc) · 1.97 KB
/
Copy pathindex.js
File metadata and controls
103 lines (88 loc) · 1.97 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
const crypto = require('crypto')
function créerPosteur(conn) {
conn.write('CC')
conn.write('Z')
const somme = crypto.createHash('md5')
somme.on('data', (clef) => {
conn.write(clef.toString('hex'))
conn.end()
})
return somme
}
function incrémenter(serrure, longueur) {
for (let [i, v] of serrure.entries()) {
if (v < 255) {
serrure[i]++
if (i >= longueur) {
longueur = i + 1;
}
return [serrure, longueur]
} else {
serrure[i] = 0
}
}
let nouvelleSerrure = Buffer.alloc(2*serrure.length)
serrure.copy(nouvelleSerrure)
nouvelleSerrure[serrure.length] = 1
return [nouvelleSerrure, serrure.length+1]
}
function trouverSerrure(clef, serrure, longueur) {
return new Promise((succès, erreur) => {
const somme = crypto.createHash('md5')
somme.on('data', (clefCandidate) => {
if (clefCandidate.equals(clef)) {
succès(serrure.slice(0, longueur))
} else {
trouverSerrure(clef, ...incrémenter(serrure, longueur))
.then(succès)
.catch(erreur)
}
})
somme.write(serrure.slice(0, longueur))
somme.end()
})
}
function créerAppliqué(conn) {
return new Promise((succès, erreur) => {
let ccReçu = false
let zReçu = false
let clefHex = ''
conn.on('data', tampon => {
if (!ccReçu) {
if (tampon.slice(0, 2).toString() == 'CC') {
ccReçu = true
tampon = tampon.slice(2)
} else {
conn.end()
return erreur(new Error('Message CC non reçu'))
}
}
if (tampon.length == 0) {
return
}
if (!zReçu) {
if (tampon.slice(0, 1).toString() == 'Z') {
zReçu = true
tampon = tampon.slice(1)
} else {
conn.end()
return erreur(new Error('Message Z non reçu'))
}
}
clefHex += tampon.toString()
})
conn.on('end', () => {
if (!ccReçu || !zReçu) {
return
}
const clef = Buffer.from(clefHex, 'hex')
trouverSerrure(clef, Buffer.alloc(512), 0)
.then(succès)
.catch(erreur)
})
})
}
module.exports = {
créerPosteur,
créerAppliqué
}