mocksaml/utils/certificate.ts

47 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-02-23 13:48:20 +00:00
import { asn1, pki, util } from 'node-forge';
2022-02-21 14:31:47 +00:00
2022-02-28 19:12:21 +00:00
const fetchPublicKey = (): string => {
return Buffer.from(process.env.PUBLIC_KEY!, 'base64').toString('ascii');
2022-02-21 14:31:47 +00:00
};
2022-02-28 19:12:21 +00:00
const fetchPrivateKey = (): string => {
return Buffer.from(process.env.PRIVATE_KEY!, 'base64').toString('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-25 20:12:28 +00:00
function GetKeyInfo(this: any, x509Certificate: string, signatureConfig: any = {}) {
2022-02-23 13:48:20 +00:00
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,
};