cngn-typescript-library
Version:
A lightweight Typescript library to give you the best experience with managing your cNGN merchant account
45 lines (44 loc) • 2.36 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Ed25519Crypto = void 0;
const libsodium_wrappers_1 = __importDefault(require("libsodium-wrappers"));
const buffer_1 = require("buffer");
class Ed25519Crypto {
static async initialize() {
if (!this.isInitialized) {
await libsodium_wrappers_1.default.ready;
this.isInitialized = true;
}
}
static parseOpenSSHPrivateKey(privateKey) {
const lines = privateKey.split('\n');
const base64PrivateKey = lines.slice(1, -1).join('');
const privateKeyBuffer = buffer_1.Buffer.from(base64PrivateKey, 'base64');
const keyDataStart = privateKeyBuffer.indexOf(buffer_1.Buffer.from([0x00, 0x00, 0x00, 0x40]));
if (keyDataStart === -1) {
throw new Error('Unable to find Ed25519 key data');
}
return new Uint8Array(privateKeyBuffer.subarray(keyDataStart + 4, keyDataStart + 68));
}
static async decryptWithPrivateKey(ed25519PrivateKey, encryptedData) {
await this.initialize();
try {
const fullPrivateKey = this.parseOpenSSHPrivateKey(ed25519PrivateKey);
const curve25519PrivateKey = libsodium_wrappers_1.default.crypto_sign_ed25519_sk_to_curve25519(fullPrivateKey);
const encryptedBuffer = buffer_1.Buffer.from(encryptedData, 'base64');
const nonce = encryptedBuffer.subarray(0, libsodium_wrappers_1.default.crypto_box_NONCEBYTES);
const ephemeralPublicKey = encryptedBuffer.subarray(-libsodium_wrappers_1.default.crypto_box_PUBLICKEYBYTES);
const ciphertext = encryptedBuffer.subarray(libsodium_wrappers_1.default.crypto_box_NONCEBYTES, -libsodium_wrappers_1.default.crypto_box_PUBLICKEYBYTES);
const decrypted = libsodium_wrappers_1.default.crypto_box_open_easy(ciphertext, nonce, ephemeralPublicKey, curve25519PrivateKey);
return libsodium_wrappers_1.default.to_string(decrypted);
}
catch (error) {
throw new Error(`Failed to decrypt with the provided Ed25519 private key: ${error}`);
}
}
}
exports.Ed25519Crypto = Ed25519Crypto;
Ed25519Crypto.isInitialized = false;