|
| 1 | +import pem from 'pem'; |
| 2 | +import fs from 'fs'; |
| 3 | +import path from 'path'; |
| 4 | +import os from 'os'; |
| 5 | +import crypto from 'crypto'; |
| 6 | + |
| 7 | +function ensureOpenSsl() { |
| 8 | + if (os.platform() === 'win32') { |
| 9 | + pem.config({ pathOpenSSL: 'C:/Program Files/OpenSSL-Win64/bin/openssl.exe' }); |
| 10 | + } |
| 11 | +} |
| 12 | + |
| 13 | +export function createSelfSignedCertificateIfNotExists(certPath, keyPath, password) { |
| 14 | + const certFullPath = path.join(__dirname, certPath); |
| 15 | + return new Promise((resolve) => { |
| 16 | + if (!fs.existsSync(certFullPath)) { |
| 17 | + ensureOpenSsl(); |
| 18 | + pem.createCertificate({ selfSigned: true, serviceKeyPassword: password, days: 365 }, (err, result) => { |
| 19 | + fs.writeFileSync(certFullPath, result.certificate); |
| 20 | + fs.writeFileSync(path.join(__dirname, keyPath), result.serviceKey); |
| 21 | + if (err) { |
| 22 | + // eslint-disable-next-line no-console |
| 23 | + console.error(err); |
| 24 | + } |
| 25 | + resolve(); |
| 26 | + }); |
| 27 | + } else { |
| 28 | + resolve(); |
| 29 | + } |
| 30 | + }); |
| 31 | +} |
| 32 | + |
| 33 | +export function getSerializedCertificate(certPath) { |
| 34 | + const pfx = fs.readFileSync(path.join(__dirname, certPath)); |
| 35 | + const pfxAsString = pfx.toString().replace(/(\r\n|\n|\r|-|BEGIN|END|CERTIFICATE|\s)/gm, ''); |
| 36 | + return pfxAsString; |
| 37 | +} |
| 38 | + |
| 39 | +export function getPrivateKey(keyPath) { |
| 40 | + const privateKey = fs.readFileSync(path.join(__dirname, keyPath), 'utf8'); |
| 41 | + return privateKey; |
| 42 | +} |
| 43 | + |
| 44 | +export function decryptSymetricKey(base64encodedKey, keyPath) { |
| 45 | + const asymetricPrivateKey = getPrivateKey(keyPath); |
| 46 | + const decodedKey = Buffer.from(base64encodedKey, 'base64'); |
| 47 | + const decryptedSymetricKey = crypto.privateDecrypt(asymetricPrivateKey, decodedKey); |
| 48 | + return decryptedSymetricKey; |
| 49 | +} |
| 50 | + |
| 51 | +export function decryptPayload(base64encodedPayload, decryptedSymetricKey) { |
| 52 | + const iv = Buffer.alloc(16, 0); |
| 53 | + decryptedSymetricKey.copy(iv, 0, 0, 16); |
| 54 | + const decipher = crypto.createDecipheriv('aes-256-cbc', decryptedSymetricKey, iv); |
| 55 | + let decryptedPayload = decipher.update(base64encodedPayload, 'base64', 'utf8'); |
| 56 | + decryptedPayload += decipher.final('utf8'); |
| 57 | + return decryptedPayload; |
| 58 | +} |
| 59 | + |
| 60 | +export function verifySignature(base64encodedSignature, base64encodedPayload, decryptedSymetricKey) { |
| 61 | + const hmac = crypto.createHmac('sha256', decryptedSymetricKey); |
| 62 | + hmac.write(base64encodedPayload, 'base64'); |
| 63 | + return base64encodedSignature === hmac.digest('base64'); |
| 64 | +} |
0 commit comments