2021-08-12 19:27:58 +00:00
|
|
|
import {
|
|
|
|
arrayBufferToString,
|
|
|
|
toBase64,
|
|
|
|
} from "pvutils";
|
|
|
|
import { formatPEM } from "./formatPEM.js";
|
|
|
|
|
2021-08-16 16:20:29 +00:00
|
|
|
export function pkijsToBase64(pkijsObj) {
|
2021-08-12 19:27:58 +00:00
|
|
|
return new Promise(async (resolve, reject) => {
|
2021-08-16 16:20:29 +00:00
|
|
|
switch(pkijsObj.__proto__.constructor.name) {
|
|
|
|
case "CryptoKey":
|
|
|
|
let arrayBuf = new ArrayBuffer(0);
|
2021-08-12 19:27:58 +00:00
|
|
|
|
2021-08-16 16:20:29 +00:00
|
|
|
if (pkijsObj.type == "private")
|
|
|
|
arrayBuf = await window.cryptoEngine.exportKey("pkcs8", pkijsObj);
|
|
|
|
else
|
|
|
|
arrayBuf = await window.cryptoEngine.exportKey("spki", pkijsObj);
|
|
|
|
|
|
|
|
resolve(toBase64(arrayBufferToString(arrayBuf)));
|
|
|
|
break;
|
2021-08-12 19:27:58 +00:00
|
|
|
|
2021-08-16 16:20:29 +00:00
|
|
|
case "CertificationRequest":
|
|
|
|
resolve(toBase64(arrayBufferToString(pkijsObj.toSchema().toBER(false))));
|
|
|
|
break;
|
|
|
|
}
|
2021-08-12 19:27:58 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-08-16 16:20:29 +00:00
|
|
|
export function pkijsToPem(pkijsObj) {
|
2021-08-12 19:27:58 +00:00
|
|
|
return new Promise(async (resolve, reject) => {
|
2021-08-16 16:20:29 +00:00
|
|
|
switch(pkijsObj.__proto__.constructor.name) {
|
|
|
|
case "CryptoKey":
|
|
|
|
let privKeyExported = await window.cryptoEngine.exportKey("pkcs8", pkijsObj);
|
|
|
|
let privKeyBody = formatPEM(
|
|
|
|
toBase64(
|
|
|
|
String.fromCharCode.apply(null, new Uint8Array(privKeyExported))
|
|
|
|
)
|
|
|
|
);
|
2021-08-17 19:36:12 +00:00
|
|
|
resolve(`-----BEGIN PRIVATE KEY-----\r\n${privKeyBody}\r\n-----END PRIVATE KEY-----\r\n`);
|
2021-08-16 16:20:29 +00:00
|
|
|
break;
|
2021-08-12 19:27:58 +00:00
|
|
|
|
2021-08-16 16:20:29 +00:00
|
|
|
case "CertificationRequest":
|
|
|
|
let resPem = "-----BEGIN CERTIFICATE REQUEST-----\r\n";
|
|
|
|
resPem = `${resPem}${formatPEM(
|
|
|
|
toBase64(arrayBufferToString(pkijsObj.toSchema().toBER(false)))
|
|
|
|
)}`;
|
|
|
|
resolve(`${resPem}\r\n-----END CERTIFICATE REQUEST-----\r\n`);
|
|
|
|
break;
|
|
|
|
}
|
2021-08-12 19:27:58 +00:00
|
|
|
});
|
2021-08-19 11:48:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function pemToBase64(pem) {
|
|
|
|
return pem.replace(/(-----(BEGIN|END) CERTIFICATE-----|\n)/g, "");
|
2021-08-12 19:27:58 +00:00
|
|
|
}
|