reciprocate.js
2.3 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
'use strict';
var RSA = require('../').RSA;
var fs = require('fs');
var path = require('path');
var privkeyPemRef = fs.readFileSync(path.join(__dirname, 'privkey.pem'), 'ascii');
var privkeyJwkRef = JSON.parse(fs.readFileSync(path.join(__dirname, 'privkey.jwk'), 'ascii'));
var refs = {
privPem: RSA.exportPrivatePem({ privateKeyJwk: privkeyJwkRef })
, privJwk: RSA.exportPrivateJwk({ privateKeyPem: privkeyPemRef })
};
var hasUrsa;
var imported;
try {
hasUrsa = require('ursa') && true;
} catch(e) {
hasUrsa = false;
}
//
//
// PEM tests
//
//
console.log('JWK -> PEM ?', privkeyPemRef === refs.privPem);
if (privkeyPemRef !== refs.privPem) {
// Watch out for tricky whitespaces (\n instead of \r\n, trailing \r\n, etc)
console.log('REF:');
console.log(JSON.stringify(privkeyPemRef));
console.log('GEN:');
console.log(JSON.stringify(refs.privPem));
throw new Error("Failed to validate importedJwk against referencePem");
}
console.log('PEM -> _ -> PEM ?', privkeyPemRef === refs.privPem);
if (hasUrsa) {
imported = RSA.import({ privateKeyPem: privkeyPemRef });
refs.privPem2 = RSA.exportPrivatePem({ _ursa: imported._ursa });
}
else {
imported = RSA.import({ privateKeyPem: privkeyPemRef });
refs.privPem2 = RSA.exportPrivatePem(imported);
}
if (privkeyPemRef !== refs.privPem2) {
console.log('REF:');
console.log(JSON.stringify(privkeyPemRef));
console.log('GEN:');
console.log(JSON.stringify(refs.privPem2));
throw new Error("Failed to validate importedPem against referencePem");
}
//
//
// JWK tests
//
//
console.log('PEM -> JWK ?', privkeyJwkRef.n === refs.privJwk.n);
if (![ 'kty', 'n', 'e', 'p', 'q', 'dp', 'dq', 'qi', 'd' ].every(function (k) {
return privkeyJwkRef[k] === refs.privJwk[k];
})) {
console.log('REF:');
console.log(privkeyJwkRef);
console.log('GEN:');
console.log(refs.privJwk);
throw new Error("Failed to validate importedPem against referenceJwk");
}
imported = RSA.import({ privateKeyJwk: privkeyJwkRef });
refs.privJwk2 = RSA.exportPrivateJwk(imported);
console.log('JWK -> _ -> JWK ?', privkeyJwkRef.n === refs.privJwk2.n);
if (privkeyJwkRef.n !== refs.privJwk2.n) {
console.log('REF:');
console.log(privkeyJwkRef);
console.log('GEN:');
console.log(refs.privJwk2);
throw new Error("Failed to validate importedJwk against referenceJwk");
}
console.log('');