-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
202 lines (186 loc) · 6.34 KB
/
index.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
'use strict'
/**
* Signer NODEJS Ministerio de Hacienda XADES-EPES
* Made by Andres Castillo @aazcast
* Thanks to: https://github.com/PeculiarVentures/xadesjs/issues/54
*/
/**
* Module dependencies
*/
const forge = require('node-forge');
const { Crypto } = require('@peculiar/webcrypto');
const xades = require('xadesjs');
const xmlCore = require('xml-core');
const {Convert} = require('pvtsutils');
const moment = require('moment-timezone');
// Preset
const crypto = new Crypto();
xades.Application.setEngine("OpenSSL", crypto);
moment.tz.setDefault("America/Costa_Rica");
/**
* Main function to sign one XML
*
* @param {string} xmlString XML in string.
* @param {string} key P12 in base64
* @param {string} pass Passphrase
*/
exports.sign = async (xmlString, key, pass) => {
try {
const data = await separateP12(key, pass);
const xmlSigned = await signXML(xmlString, data.cert64, data.pkey64, data.pbkey64);
return xmlSigned;
} catch (err) {
throw err;
}
}
exports.verifySignature = async (key, pass) => {
try {
const p12base64 = key;
const passphrase = pass;
const asn = forge.asn1.fromDer(forge.util.decode64(p12base64));
const p12 = forge.pkcs12.pkcs12FromAsn1(asn, true, passphrase);
const certBags = p12.getBags({ bagType: forge.pki.oids.certBag })[forge.pki.oids.certBag];
const expiresOn = certBags[0].cert.validity.notAfter;
const date = moment().format();
let timediff = moment(expiresOn).diff(date, 'seconds');
if (timediff < 100000 ) {
//cert is expired or expires in one day
throw err;
}
return {
isValid: true,
expiresOn
};
} catch (err) {
throw new Error('Error en la llave criptográfica y clave de la misma. Verificar la información en ATV hacienda https://www.hacienda.go.cr/ATV/Login.aspx');
}
}
/**
* Separate p12 file in three different files necessary to sign, we return three files in base64. cert and two pem files
*
* @param {string} key P12 in base64
* @param {string} pass Passphrase
*/
const separateP12 = async (key, pass) => {
try {
const p12base64 = key;
const passphrase = pass;
//We separate the p12
const asn = forge.asn1.fromDer(forge.util.decode64(p12base64));
const p12 = forge.pkcs12.pkcs12FromAsn1(asn, true, passphrase);
//We ket the ley data
const keyData = p12.getBags({ bagType: forge.pki.oids.pkcs8ShroudedKeyBag })[forge.pki.oids.pkcs8ShroudedKeyBag].concat(p12.getBags({ bagType: forge.pki.oids.keyBag })[forge.pki.oids.keyBag]);
//get the private key
const rsaPrivateKey = forge.pki.privateKeyToAsn1(keyData[0].key);
const privateKeyInfo = forge.pki.wrapRsaPrivateKey(rsaPrivateKey);
const pemPrivate = forge.pki.privateKeyInfoToPem(privateKeyInfo);
const pkey64 = await pemToBase64(pemPrivate);
//get the cert
const certBags = p12.getBags({ bagType: forge.pki.oids.certBag })[forge.pki.oids.certBag];
const finalCert = forge.pki.certificateToPem(certBags[0].cert);
const cert64 = await pemToBase64(finalCert)
//get the public key from private key
const preprivateKey = forge.pki.privateKeyFromPem(pemPrivate);
const prepublicKey = forge.pki.setRsaPublicKey(preprivateKey.n, preprivateKey.e);
const publicKey = forge.pki.publicKeyToPem(prepublicKey);
const pbkey64 = await pemToBase64(publicKey)
//return the data
const data = {
pkey64,
cert64,
pbkey64
};
return data;
} catch (err) {
throw new Error('Error en la llave criptográfica y clave de la misma. Verificar la información en ATV hacienda https://www.hacienda.go.cr/ATV/Login.aspx');
}
}
/**
* The current code have been implemented in javacript using library xadesjs
*
* @param {string} xmlString XML to sign
* @param {string} ct Base64 Cert
* @param {string} pk Base64 PublicKey pem
* @param {string} pbk Base64 PrivateKey pem
*/
const signXML = async (xmlString, ct, pk, pbk) => {
try {
const uuidv4 = generateId();
const hash = "SHA-256";
const alg = {
name: "RSASSA-PKCS1-v1_5",
hash: hash,
publicExponent: new Uint8Array([1, 0, 1]),
modulusLength: 2048,
}
// Read cert
const certDer = Convert.FromBase64(ct);
// Read public key
const publicKeyDer = Convert.FromBase64(pbk);
const publicKey = await crypto.subtle.importKey("spki", publicKeyDer, alg, true, ["verify"]);
// Read private key
const keyDer = Convert.FromBase64(pk);
const key = await crypto.subtle.importKey("pkcs8", keyDer, alg, false, ["sign"]);
// XAdES-EPES
let xml = xades.Parse(xmlString);
const xadesXml = new xades.SignedXml();
const x509 = ct;
const referenceId = uuidv4;
//Create signature
const signature = await xadesXml.Sign( // Signing document
alg, // algorithm
key, // key
xml, // document
{ // options
keyValue: publicKey,
references: [
{
id: "Reference-" + referenceId,
uri: "",
hash: hash,
transforms: [
// "c14n",
"enveloped",
],
}
],
signerRole: {
claimed: ["ObligadoTributario"]
},
x509: [x509],
signingCertificate: x509,
policy: {
hash: "SHA-1",
identifier: {
qualifier: "OIDAsURI",
value: "https://tribunet.hacienda.go.cr/docs/esquemas/2016/v4/Resolucion%20Comprobantes%20Electronicos%20%20DGT-R-48-2016.pdf",
}
},
});
// append signature
xml.documentElement.appendChild(signature.GetXml());
// serialize XML
const sXML = xmlCore.Stringify(xml);
const signedXml = Buffer.from(sXML).toString("base64");
return signedXml;
} catch (err) {
throw err;
}
}
//Convert pem to base64
const pemToBase64 = (pem) => {
return new Promise(function (resolve, reject) {
const pemfinal = pem
// remove BEGIN/END
.replace(/-----(BEGIN|END)[\w\d\s]+-----/g, "")
// remove \r, \n
.replace(/[\r\n]/g, "");
resolve(pemfinal);
});
}
//Generate ID for reference id
const generateId = () => {
return (`${1e7}-${1e3}-${4e3}-${8e3}-${1e11}`).replace(/[018]/g, (c) =>
(c ^ (crypto.getRandomValues(new Uint8Array(1)))[0] & 15 >> c / 4).toString(16)
);
}