1
|
var test = require('tape')
|
2
|
var DES = require('./')
|
3
|
var modes = require('./modes')
|
4
|
var crypto = require('crypto')
|
5
|
|
6
|
Object.keys(modes).forEach(function (mode) {
|
7
|
test(mode, function (t) {
|
8
|
var i = 0
|
9
|
while (++i < 10) {
|
10
|
runOnce(i)
|
11
|
}
|
12
|
function runOnce (i) {
|
13
|
t.test('run: ' + i, function (t) {
|
14
|
t.plan(2)
|
15
|
var key = crypto.randomBytes(modes[mode].key)
|
16
|
var iv = crypto.randomBytes(modes[mode].iv)
|
17
|
var text = crypto.randomBytes(200)
|
18
|
var ourEncrypt
|
19
|
try {
|
20
|
ourEncrypt = new DES({
|
21
|
mode: mode,
|
22
|
key: key,
|
23
|
iv: iv
|
24
|
})
|
25
|
} catch (e) {
|
26
|
t.notOk(e, e.stack)
|
27
|
}
|
28
|
var nodeEncrypt
|
29
|
try {
|
30
|
nodeEncrypt = crypto.createCipheriv(mode, key, iv)
|
31
|
} catch (e) {
|
32
|
t.notOk(e, e.stack)
|
33
|
}
|
34
|
var ourCipherText = Buffer.concat([ourEncrypt.update(text), ourEncrypt.final()])
|
35
|
var nodeCipherText = Buffer.concat([nodeEncrypt.update(text), nodeEncrypt.final()])
|
36
|
t.equals(nodeCipherText.toString('hex'), ourCipherText.toString('hex'))
|
37
|
var ourDecrypt = new DES({
|
38
|
mode: mode,
|
39
|
key: key,
|
40
|
iv: iv,
|
41
|
decrypt: true
|
42
|
})
|
43
|
var plainText = Buffer.concat([ourDecrypt.update(ourCipherText), ourDecrypt.final()])
|
44
|
t.equals(text.toString('hex'), plainText.toString('hex'))
|
45
|
})
|
46
|
t.test('run text: ' + i, function (t) {
|
47
|
t.plan(2)
|
48
|
var key = crypto.randomBytes(32).toString('base64').slice(0, modes[mode].key)
|
49
|
var iv = crypto.randomBytes(32).toString('base64').slice(0, modes[mode].iv)
|
50
|
var text = crypto.randomBytes(200)
|
51
|
var ourEncrypt
|
52
|
try {
|
53
|
ourEncrypt = new DES({
|
54
|
mode: mode,
|
55
|
key: key,
|
56
|
iv: iv
|
57
|
})
|
58
|
} catch (e) {
|
59
|
t.notOk(e, e.stack)
|
60
|
}
|
61
|
var nodeEncrypt
|
62
|
try {
|
63
|
nodeEncrypt = crypto.createCipheriv(mode, key, iv)
|
64
|
} catch (e) {
|
65
|
t.notOk(e, e.stack)
|
66
|
}
|
67
|
var ourCipherText = Buffer.concat([ourEncrypt.update(text), ourEncrypt.final()])
|
68
|
var nodeCipherText = Buffer.concat([nodeEncrypt.update(text), nodeEncrypt.final()])
|
69
|
t.equals(nodeCipherText.toString('hex'), ourCipherText.toString('hex'))
|
70
|
var ourDecrypt = new DES({
|
71
|
mode: mode,
|
72
|
key: key,
|
73
|
iv: iv,
|
74
|
decrypt: true
|
75
|
})
|
76
|
var plainText = Buffer.concat([ourDecrypt.update(ourCipherText), ourDecrypt.final()])
|
77
|
t.equals(text.toString('hex'), plainText.toString('hex'))
|
78
|
})
|
79
|
}
|
80
|
})
|
81
|
})
|