UNPKG

@funded-labs/plug-controller

Version:

Internet Computer Plug wallet's controller

70 lines (69 loc) 2.55 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getIdentityFromPem = exports.parseSec256K1 = exports.parseEd25519 = void 0; const identity_1 = __importDefault(require("./secpk256k1/identity")); const ed25519Identity_1 = __importDefault(require("./ed25519/ed25519Identity")); const constants_1 = require("../account/constants"); const errors_1 = require("../../errors"); const ED25519_KEY_INIT = '3053020101300506032b657004220420'; const ED25519_KEY_SEPARATOR = 'a123032100'; const ED25519_OID = '06032b6570'; const SEC256k1_KEY_INIT = '30740201010420'; const SEC256k1_KEY_SEPARATOR = 'a00706052b8104000aa144034200'; const SEC256k1_OID = '06052b8104000a'; const parseEd25519 = (pem) => { const raw = Buffer.from(pem, 'base64') .toString('hex'); if (!raw.substring(0, 24).includes(ED25519_OID)) { return undefined; } const trimRaw = raw .replace(ED25519_KEY_INIT, '') .replace(ED25519_KEY_SEPARATOR, ''); try { const key = new Uint8Array(Buffer.from(trimRaw, 'hex')); const identity = ed25519Identity_1.default.fromSecretKey(key); const type = constants_1.Types.pem25519; return { identity, type }; } catch (_a) { return undefined; } }; exports.parseEd25519 = parseEd25519; const parseSec256K1 = (pem) => { const raw = Buffer.from(pem, 'base64') .toString('hex'); if (!raw.includes(SEC256k1_OID)) { return undefined; } const trimRaw = raw .replace(SEC256k1_KEY_INIT, '') .replace(SEC256k1_KEY_SEPARATOR, ''); try { const key = new Uint8Array(Buffer.from(trimRaw.substring(0, 64), 'hex')); const identity = identity_1.default.fromSecretKey(key); const type = constants_1.Types.pem256k1; return { identity, type }; } catch (_a) { return undefined; } }; exports.parseSec256K1 = parseSec256K1; const getIdentityFromPem = (pem) => { const trimedPem = pem .replace(/(-{5}.*-{5})/g, '') .replace('\n', '') // Sepk256k1 keys .replace('BgUrgQQACg==', '') .trim(); const parsedIdentity = (0, exports.parseEd25519)(trimedPem) || (0, exports.parseSec256K1)(trimedPem); if (!parsedIdentity) throw new Error(errors_1.ERROR_CODES.INVALID_KEY); return parsedIdentity; }; exports.getIdentityFromPem = getIdentityFromPem;