mocksaml/utils/certificate.ts

49 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-02-21 14:31:47 +00:00
import { promises as fs } from 'fs';
2022-02-23 13:48:20 +00:00
import { asn1, pki, util } from 'node-forge';
2022-02-21 14:31:47 +00:00
import path from 'path';
2022-02-21 15:36:25 +00:00
const fetchPublicKey = async (): Promise<string> => {
2022-02-21 16:23:43 +00:00
return await fs.readFile(path.join('data', 'public.crt'), 'ascii');
2022-02-21 14:31:47 +00:00
};
2022-02-21 15:36:25 +00:00
const fetchPrivateKey = async (): Promise<string> => {
2022-02-21 16:23:43 +00:00
return await fs.readFile(path.join('data', 'key.pem'), 'ascii');
2022-02-22 06:14:12 +00:00
};
2022-02-21 14:31:47 +00:00
2022-02-23 13:48:20 +00:00
function getPublicKeyPemFromCertificate(x509Certificate: string) {
const certDerBytes = util.decode64(x509Certificate);
const obj = asn1.fromDer(certDerBytes);
const cert = pki.certificateFromAsn1(obj);
return pki.publicKeyToPem(cert.publicKey);
}
2022-02-21 15:36:25 +00:00
const stripCertHeaderAndFooter = (cert: string): string => {
cert = cert.replace(/-+BEGIN CERTIFICATE-+\r?\n?/, '');
cert = cert.replace(/-+END CERTIFICATE-+\r?\n?/, '');
cert = cert.replace(/\r\n/g, '\n');
return cert;
2022-02-21 14:31:47 +00:00
};
2022-02-23 13:48:20 +00:00
function GetKeyInfo(x509Certificate: string, signatureConfig: any = {}) {
x509Certificate = stripCertHeaderAndFooter(x509Certificate);
this.getKeyInfo = () => {
const prefix = signatureConfig.prefix ? `${signatureConfig.prefix}:` : '';
return `<${prefix}X509Data><${prefix}X509Certificate>${x509Certificate}</${prefix}X509Certificate></${prefix}X509Data>`;
};
this.getKey = () => {
return getPublicKeyPemFromCertificate(x509Certificate).toString();
};
}
export {
fetchPublicKey,
fetchPrivateKey,
stripCertHeaderAndFooter,
getPublicKeyPemFromCertificate,
GetKeyInfo,
};