-
Notifications
You must be signed in to change notification settings - Fork 5
/
rsa.js
35 lines (26 loc) · 771 Bytes
/
rsa.js
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
var hash = require('hash.js');
var brorand = require('brorand');
var bn = require('bn.js');
var asn1 = require('./asn1');
exports.sign = function sign(data, keyData) {
var toSign = new hash.sha512().update(data).digest();
toSign = asn1.Signature.encode({
algorithm: {
algorithm: asn1.SHA512
},
digest: toSign
}, 'der');
var len = keyData.modulus.byteLength();
// PKCS1 padding
var pad = [ 0, 1 ];
while (toSign.length + pad.length + 1 < len)
pad.push(0xff);
pad.push(0x00);
for (var i = 0; i < toSign.length; i++)
pad.push(toSign[i]);
toSign = pad;
var red = bn.mont(keyData.modulus);
toSign = new bn(toSign).toRed(red);
toSign = toSign.redPow(keyData.privateExponent);
return toSign.fromRed().toArray();
};