1
|
var parseKeys = require('parse-asn1')
|
2
|
var mgf = require('./mgf')
|
3
|
var xor = require('./xor')
|
4
|
var BN = require('bn.js')
|
5
|
var crt = require('browserify-rsa')
|
6
|
var createHash = require('create-hash')
|
7
|
var withPublic = require('./withPublic')
|
8
|
var Buffer = require('safe-buffer').Buffer
|
9
|
|
10
|
module.exports = function privateDecrypt (privateKey, enc, reverse) {
|
11
|
var padding
|
12
|
if (privateKey.padding) {
|
13
|
padding = privateKey.padding
|
14
|
} else if (reverse) {
|
15
|
padding = 1
|
16
|
} else {
|
17
|
padding = 4
|
18
|
}
|
19
|
|
20
|
var key = parseKeys(privateKey)
|
21
|
var k = key.modulus.byteLength()
|
22
|
if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) {
|
23
|
throw new Error('decryption error')
|
24
|
}
|
25
|
var msg
|
26
|
if (reverse) {
|
27
|
msg = withPublic(new BN(enc), key)
|
28
|
} else {
|
29
|
msg = crt(enc, key)
|
30
|
}
|
31
|
var zBuffer = Buffer.alloc(k - msg.length)
|
32
|
msg = Buffer.concat([zBuffer, msg], k)
|
33
|
if (padding === 4) {
|
34
|
return oaep(key, msg)
|
35
|
} else if (padding === 1) {
|
36
|
return pkcs1(key, msg, reverse)
|
37
|
} else if (padding === 3) {
|
38
|
return msg
|
39
|
} else {
|
40
|
throw new Error('unknown padding')
|
41
|
}
|
42
|
}
|
43
|
|
44
|
function oaep (key, msg) {
|
45
|
var k = key.modulus.byteLength()
|
46
|
var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
|
47
|
var hLen = iHash.length
|
48
|
if (msg[0] !== 0) {
|
49
|
throw new Error('decryption error')
|
50
|
}
|
51
|
var maskedSeed = msg.slice(1, hLen + 1)
|
52
|
var maskedDb = msg.slice(hLen + 1)
|
53
|
var seed = xor(maskedSeed, mgf(maskedDb, hLen))
|
54
|
var db = xor(maskedDb, mgf(seed, k - hLen - 1))
|
55
|
if (compare(iHash, db.slice(0, hLen))) {
|
56
|
throw new Error('decryption error')
|
57
|
}
|
58
|
var i = hLen
|
59
|
while (db[i] === 0) {
|
60
|
i++
|
61
|
}
|
62
|
if (db[i++] !== 1) {
|
63
|
throw new Error('decryption error')
|
64
|
}
|
65
|
return db.slice(i)
|
66
|
}
|
67
|
|
68
|
function pkcs1 (key, msg, reverse) {
|
69
|
var p1 = msg.slice(0, 2)
|
70
|
var i = 2
|
71
|
var status = 0
|
72
|
while (msg[i++] !== 0) {
|
73
|
if (i >= msg.length) {
|
74
|
status++
|
75
|
break
|
76
|
}
|
77
|
}
|
78
|
var ps = msg.slice(2, i - 1)
|
79
|
|
80
|
if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) {
|
81
|
status++
|
82
|
}
|
83
|
if (ps.length < 8) {
|
84
|
status++
|
85
|
}
|
86
|
if (status) {
|
87
|
throw new Error('decryption error')
|
88
|
}
|
89
|
return msg.slice(i)
|
90
|
}
|
91
|
function compare (a, b) {
|
92
|
a = Buffer.from(a)
|
93
|
b = Buffer.from(b)
|
94
|
var dif = 0
|
95
|
var len = a.length
|
96
|
if (a.length !== b.length) {
|
97
|
dif++
|
98
|
len = Math.min(a.length, b.length)
|
99
|
}
|
100
|
var i = -1
|
101
|
while (++i < len) {
|
102
|
dif += (a[i] ^ b[i])
|
103
|
}
|
104
|
return dif
|
105
|
}
|