-
Notifications
You must be signed in to change notification settings - Fork 0
/
digSigAPI.js
296 lines (237 loc) · 9.26 KB
/
digSigAPI.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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
function digSigAPI(){
'use strict';
let digSigKeys = {};
let certInfoObj;
function generateKey(){
return window.crypto.subtle.generateKey(
{
name: 'RSASSA-PKCS1-v1_5',
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]), // 24 bit representation of 65537
hash: {name: "SHA-256"}
},
true, // can extract it later if we want
['sign', 'verify']
)
.then(function(key){
digSigKeys = key;
return key;
});
}//generateKey
function sign(buffer){
return window.crypto.subtle.sign(
{name: 'RSASSA-PKCS1-v1_5'},
digSigKeys.privateKey,
buffer
)
}
function verify(signature, buffer){
return window.crypto.subtle.verify(
{name: 'RSASSA-PKCS1-v1_5'},
digSigKeys.publicKey,
signature,
buffer
)
}
function importKey(keyBuffer){
return window.crypto.subtle.importKey(
'spki',
keyBuffer,
{
name: 'RSASSA-PKCS1-v1_5',
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]), // 24 bit representation of 65537
hash: {
name: 'SHA-256'
}
},
true,
['verify']
)
.then(function(newKey){
digSigKeys.publicKey = newKey;
return newKey;
})
}
function exportKey(){
return window.crypto.subtle.exportKey(
'spki',
digSigKeys.publicKey
)
}
function createCertificate(_commonName, _organization, _organizationUnit, _countryCode, _keyPair) {
let keyPair = _keyPair;
let commonName = _commonName;
let organization = _organization;
let organizationUnit = _organizationUnit;
let countryCode = _countryCode;
if (!commonName) {
console.log("You must enter a name for the certificate.");
return;
}
if (countryCode.length !== 2) {
console.log("Country codes must be two characters long.");
return;
}
countryCode = countryCode.toUpperCase();
let certAsPemText;
let publicKeyAsPemText;
let privateKeyAsPemText;
return buildCertificateObject(commonName, organization, organizationUnit, countryCode, keyPair)
//convert (cert + public key + private key) to base64 string and pem files
.then(function(cert) {
let pemCert = convertBinaryToPem(cert.toSchema(true).toBER(false), "CERTIFICATE");
certAsPemText = pemCert;
return window.crypto.subtle.exportKey('spki', keyPair.publicKey).
then(function(spki) {
let pemPublicKey = convertBinaryToPem(spki, "PUBLIC KEY");
publicKeyAsPemText = pemPublicKey;
certInfoObj = {
publicKeyAsPemText: publicKeyAsPemText,
certAsPemText: certAsPemText,
}
return certInfoObj;
});
})
}
// Returns a Promise yielding the certificate object
function buildCertificateObject(commonName, organization, organizationUnit, countryCode, keyPair) {
var cert = new org.pkijs.simpl.CERT();
setSerialNumber(cert, Date.now());
setSubject(cert, countryCode, organization, organizationUnit, commonName);
setIssuer(cert, countryCode, organization, organizationUnit, commonName);
setValidityPeriod(cert, new Date(), 30); // Good from today for 30 days
setEmptyExtensions(cert);
setCABit(cert, false);
//digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign, cRLSign
setKeyUsage(cert, true, true, false, false, false, true, true);
setSignatureAlgorithm(cert, "1.2.840.113549.1.1.11"); // RSA with SHA-256
return setPublicKey(cert, keyPair.publicKey).
then(function() {return signCert(cert, "1.2.840.113549.1.1.11", keyPair.privateKey)}).
then(function() {return cert});
// Helper functions
function setSerialNumber(cert, serialNumber) {
cert.serialNumber = new org.pkijs.asn1.INTEGER({value: serialNumber});;
}
function setSubject(cert, countryCode, organization, organizationUnit, commonName) {
setEntity(cert.subject, countryCode, organization, organizationUnit, commonName);
}
function setIssuer(cert, countryCode, organization, organizationUnit, commonName) {
setEntity(cert.issuer, countryCode, organization, organizationUnit, commonName);
}
function setEntity(entity, countryCode, organization, organizationUnit, commonName) {
if (countryCode) {
entity.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({
type: "2.5.4.6", //countryCode
value: new org.pkijs.asn1.PRINTABLESTRING({value: countryCode})
}));
}
if (organization) {
entity.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({
type: "2.5.4.10", //Organization
value: new org.pkijs.asn1.PRINTABLESTRING({value: organization})
}));
}
if (organizationUnit) {
entity.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({
type: "2.5.4.11", //Organization Unit
value: new org.pkijs.asn1.PRINTABLESTRING({value: organizationUnit})
}));
}
if (commonName) {
entity.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({
type: "2.5.4.3", //commonName
value: new org.pkijs.asn1.PRINTABLESTRING({value: commonName})
}));
}
}
function setValidityPeriod(cert, startDate, durationInDays) {
// Normalize to midnight
var start = new Date(startDate);
start.setHours(0);
start.setMinutes(0);
start.setSeconds(0);
var end = new Date(start.getTime() + durationInDays * 24 * 60 * 60 * 1000);
cert.notBefore.value = start;
cert.notAfter.value = end;
}
function setEmptyExtensions(cert) {
cert.extensions = new Array();
}
function setCABit(cert, isCA) {
var basicConstraints = new org.pkijs.simpl.x509.BasicConstraints({
cA: isCA,
pathLenConstraint: 3
});
cert.extensions.push(new org.pkijs.simpl.EXTENSION({
extnID: "2.5.29.19",
critical: false,
extnValue: basicConstraints.toSchema().toBER(false),
parsedValue: basicConstraints
}));
}
function setKeyUsage(cert, digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign, cRLSign) {
var keyUsageBits = new ArrayBuffer(1);
var keyUsageBytes = new Uint8Array(keyUsageBits);
keyUsageBytes[0] = 0;
if (digitalSignature) {keyUsageBytes[0] |= 0x80;}
if (nonRepudiation) {keyUsageBytes[0] |= 0x40;}
if (keyEncipherment) {keyUsageBytes[0] |= 0x20;}
if (dataEncipherment) {keyUsageBytes[0] |= 0x10;}
if (keyAgreement) {keyUsageBytes[0] |= 0x08;}
if (keyCertSign) {keyUsageBytes[0] |= 0x04;}
if (cRLSign) {keyUsageBytes[0] |= 0x02;}
var keyUsage = new org.pkijs.asn1.BITSTRING({value_hex: keyUsageBits});
cert.extensions.push(new org.pkijs.simpl.EXTENSION({
extnID: "2.5.29.15",
critical: false,
extnValue: keyUsage.toBER(false),
parsedValue: keyUsage
}));
}
function setSignatureAlgorithm(cert, oid) {
cert.signatureAlgorithm.algorithm_id = oid; // In tbsCert
}
function setPublicKey(cert, publicKey) {
return cert.subjectPublicKeyInfo.importKey(publicKey);
}
function signCert(cert, oid, privateKey) {
cert.signature.algorithm_id = oid; // In actual signature
return cert.sign(privateKey);
}
}
// General helper functions
function arrayBufferToBase64String(arrayBuffer) {
var byteArray = new Uint8Array(arrayBuffer)
var byteString = '';
for (var i=0; i<byteArray.byteLength; i++) {
byteString += String.fromCharCode(byteArray[i]);
}
return btoa(byteString);
}
function convertBinaryToPem(binaryData, label) {
var base64Cert = arrayBufferToBase64String(binaryData);
var pemCert = "-----BEGIN " + label + "-----\r\n";
var nextIndex = 0;
var lineLength;
while (nextIndex < base64Cert.length) {
if (nextIndex + 64 <= base64Cert.length) {
pemCert += base64Cert.substr(nextIndex, 64) + "\r\n";
} else {
pemCert += base64Cert.substr(nextIndex) + "\r\n";
}
nextIndex += 64;
}
pemCert += "-----END " + label + "-----\r\n";
return pemCert;
}
let publicAPI = {
generateKey: generateKey,
sign: sign,
verify: verify,
importKey: importKey,
exportKey: exportKey,
createCertificate: createCertificate,
};
return publicAPI;
}