apacuana-sdk-web
Version:
Apacuana SDK for Web
116 lines • 4.53 kB
JavaScript
import * as asn1js from "asn1js";
import * as pkijs from "pkijs";
import * as forge from "node-forge";
import { getCrypto } from "pkijs";
import CryptoJS from "crypto-js";
const hashAlg = "SHA-512";
const signAlg = "RSASSA-PKCS1-v1_5";
const key = CryptoJS.enc.Utf8.parse("dRgUkXp2s5v8y/B?");
export async function generateKeyPair() {
const crypto = getCrypto();
if (crypto) {
const keyPair = await crypto.generateKey({
name: signAlg,
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: { name: hashAlg },
}, true, // Puede ser exportado
["sign", "verify"]);
return keyPair;
}
}
export async function generateCSR(keyPair, userEmail) {
const { publicKey, privateKey } = keyPair;
const pkcs10 = new pkijs.CertificationRequest();
pkcs10.version = 0;
// Definir el subject completo
const subjectDN = [
{ type: "2.5.4.6", value: new asn1js.PrintableString({ value: "VE" }) },
{
type: "1.2.840.113549.1.9.1",
value: new asn1js.IA5String({ value: userEmail }),
},
];
subjectDN.forEach((attr) => pkcs10.subject.typesAndValues.push(new pkijs.AttributeTypeAndValue(attr)));
return pkcs10.subjectPublicKeyInfo
.importKey(publicKey)
.then(() => pkcs10.sign(privateKey, hashAlg))
.then(() => {
const csr = pkcs10.toSchema().toBER(false);
return { csr, subject: pkcs10.subject };
});
}
export function transformCSR(csr) {
const csrBase64 = btoa(String.fromCharCode(...new Uint8Array(csr)));
return csrBase64;
}
export function encryptCSR(csrBase64) {
const encryptObj = {
csr: CryptoJS.AES.encrypt(csrBase64, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
}).toString(),
};
return encryptObj;
}
export async function exportPrivateKey(key) {
const crypto = getCrypto();
if (crypto) {
const exported = await crypto.exportKey("pkcs8", key);
const exportablePrivateKey = new Uint8Array(exported);
return arrayBufferToBase64(exportablePrivateKey);
}
}
function arrayBufferToBase64(buffer) {
const uint8Array = new Uint8Array(buffer);
const numberArray = Array.from(uint8Array);
const binary = String.fromCharCode.apply(null, numberArray);
return btoa(binary);
}
export async function createPKCS12(privateKey, certBase64, password) {
var _a;
const pki = forge.pki;
const asn1 = forge.asn1;
// Convertir el certificado Base64 a PEM
const certPem = `-----BEGIN CERTIFICATE-----\n${((_a = certBase64.match(/.{1,64}/g)) === null || _a === void 0 ? void 0 : _a.join("\n")) || certBase64}\n-----END CERTIFICATE-----`;
// Convertir las claves y el certificado a objetos de Forge
const privateKeyObj = pki.privateKeyFromPem(privateKey);
const certObj = pki.certificateFromPem(certPem);
// Crear el archivo PKCS#12
const p12Asn1 = forge.pkcs12.toPkcs12Asn1(privateKeyObj, [certObj], password, { algorithm: "3des" });
// Verificar contenido del SafeBag
const p12Der = asn1.toDer(p12Asn1).getBytes();
const p12Base64 = forge.util.encode64(p12Der);
return p12Base64;
}
export function createObjectStore(jsonData) {
const request = indexedDB.open("cryptoKeysDB", 1);
request.onupgradeneeded = (event) => {
var _a;
const db = (_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.result;
if (!db.objectStoreNames.contains("keys")) {
db.createObjectStore("keys", { keyPath: "id" });
console.log('Object store "keys" created.');
}
};
request.onsuccess = (event) => {
const db = event.target.result;
console.log("Database opened successfully.");
// Inserta los datos en IndexedDB
const transaction = db.transaction("keys", "readwrite");
const store = transaction.objectStore("keys");
store.put(jsonData);
transaction.oncomplete = function () {
console.log("Datos importados con éxito");
};
transaction.onerror = function () {
console.error("Error al importar los datos:", transaction.error);
};
};
request.onerror = (event) => {
console.error("Error al abrir la base de datos:", event.target.error);
};
}
export * from "./errors.js";
export * from "./indexedDB.js";
//# sourceMappingURL=index.js.map