UNPKG

@tigthor/kokocrypt

Version:

Enhanced Fortress Edition - Secure, quantum-resistant, high-performance encryption package

240 lines 10.9 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.CryptoService = void 0; const common_1 = require("@nestjs/common"); const config_1 = require("@nestjs/config"); const sodiumNative = __importStar(require("sodium-native")); const libsodium_wrappers_1 = __importDefault(require("libsodium-wrappers")); const key_provider_1 = require("../providers/key-provider"); const algorithm_type_1 = require("../types/algorithm.type"); let ntru = null; let liboqs = null; try { ntru = require('ntru'); } catch (e) { ntru = { createKeyPair: () => { throw new Error('NTRU package is not installed. Install it with npm install ntru'); }, encrypt: () => { throw new Error('NTRU package is not installed. Install it with npm install ntru'); }, decrypt: () => { throw new Error('NTRU package is not installed. Install it with npm install ntru'); } }; } try { liboqs = require('liboqs-node'); } catch (e) { liboqs = { init: async () => { }, KeyEncapsulation: class { constructor(algorithm) { throw new Error('liboqs-node package is not installed. Install it with npm install liboqs-node'); } keypair() { throw new Error('liboqs-node package is not installed. Install it with npm install liboqs-node'); } encapsulate(publicKey) { throw new Error('liboqs-node package is not installed. Install it with npm install liboqs-node'); } decapsulate(ciphertext, privateKey) { throw new Error('liboqs-node package is not installed. Install it with npm install liboqs-node'); } } }; } let CryptoService = class CryptoService { constructor(provider, configService) { this.provider = provider; this.configService = configService; } async ready() { return this.provider.getCurrentKey(); } async boxRaw(message, key) { const nonce = Buffer.allocUnsafe(sodiumNative.crypto_secretbox_NONCEBYTES); sodiumNative.randombytes_buf(nonce); const ciphertext = Buffer.allocUnsafe(message.length + sodiumNative.crypto_secretbox_MACBYTES); sodiumNative.crypto_secretbox_easy(ciphertext, message, nonce, key); const result = Buffer.allocUnsafe(nonce.length + ciphertext.length); nonce.copy(result, 0); ciphertext.copy(result, nonce.length); return result; } async unboxRaw(encryptedMessage, key) { if (encryptedMessage.length < sodiumNative.crypto_secretbox_NONCEBYTES + sodiumNative.crypto_secretbox_MACBYTES) { throw new Error('Invalid encrypted message length'); } const nonce = encryptedMessage.slice(0, sodiumNative.crypto_secretbox_NONCEBYTES); const ciphertext = encryptedMessage.slice(sodiumNative.crypto_secretbox_NONCEBYTES); const message = Buffer.allocUnsafe(ciphertext.length - sodiumNative.crypto_secretbox_MACBYTES); if (!sodiumNative.crypto_secretbox_open_easy(message, ciphertext, nonce, key)) { throw new Error('Decryption failed'); } return message; } async deriveSession(clientPublicKey, ts) { const { key: serverKey } = await this.provider.getCurrentKey(); const serverPrivateKey = serverKey.subarray(0, 32); const serverPublicKey = serverKey.subarray(32); const rx = Buffer.allocUnsafe(32); const tx = Buffer.allocUnsafe(32); sodiumNative.crypto_kx_keypair(serverPublicKey, serverPrivateKey); sodiumNative.crypto_kx_server_session_keys(rx, tx, serverPublicKey, serverPrivateKey, clientPublicKey); return { rx, tx, kid: 'session', ts, }; } async getCurrentKey() { return this.provider.getCurrentKey(); } async getKey(kid) { return this.provider.getKey(kid); } async encryptAesGcm(message, key) { await libsodium_wrappers_1.default.ready; const nonceArray = libsodium_wrappers_1.default.randombytes_buf(libsodium_wrappers_1.default.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES); const nonce = Buffer.from(nonceArray); const ciphertext = libsodium_wrappers_1.default.crypto_aead_xchacha20poly1305_ietf_encrypt(message, null, null, nonceArray, key); const result = Buffer.allocUnsafe(nonce.length + ciphertext.length); nonce.copy(result, 0); Buffer.from(ciphertext).copy(result, nonce.length); return result; } async decryptAesGcm(encryptedMessage, key) { if (encryptedMessage.length < libsodium_wrappers_1.default.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES + 16) { throw new Error('Invalid encrypted message length'); } const nonce = encryptedMessage.slice(0, libsodium_wrappers_1.default.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES); const ciphertext = encryptedMessage.slice(libsodium_wrappers_1.default.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES); await libsodium_wrappers_1.default.ready; try { const decrypted = libsodium_wrappers_1.default.crypto_aead_xchacha20poly1305_ietf_decrypt(null, ciphertext, null, nonce, key); return Buffer.from(decrypted); } catch (err) { throw new Error('Decryption failed'); } } async encryptKyber(message) { await liboqs.init(); const kem = new liboqs.KeyEncapsulation('Kyber512'); const keyPair = kem.keypair(); const keyResult = await this.provider.storeKey(Buffer.from(keyPair.secret_key), algorithm_type_1.AlgorithmType.Kyber); const encapsulation = kem.encapsulate(keyPair.public_key); const encrypted = await this.boxRaw(message, Buffer.from(encapsulation.shared_secret)); return { ciphertext: encrypted, encapsulatedKey: Buffer.from(encapsulation.ciphertext) }; } async decryptKyber(ciphertext, encapsulatedKey, privateKey) { await liboqs.init(); const kem = new liboqs.KeyEncapsulation('Kyber512'); const sharedSecret = kem.decapsulate(encapsulatedKey, privateKey); return this.unboxRaw(ciphertext, Buffer.from(sharedSecret)); } async batchEncrypt(messages, key) { const results = []; const nonces = []; for (let i = 0; i < messages.length; i++) { const nonce = Buffer.allocUnsafe(sodiumNative.crypto_secretbox_NONCEBYTES); sodiumNative.randombytes_buf(nonce); nonces.push(nonce); } await Promise.all(messages.map(async (message, index) => { const nonce = nonces[index]; const ciphertext = Buffer.allocUnsafe(message.length + sodiumNative.crypto_secretbox_MACBYTES); sodiumNative.crypto_secretbox_easy(ciphertext, message, nonce, key); const result = Buffer.allocUnsafe(nonce.length + ciphertext.length); nonce.copy(result, 0); ciphertext.copy(result, nonce.length); results[index] = result; })); return results; } async batchDecrypt(encryptedMessages, key) { const results = []; await Promise.all(encryptedMessages.map(async (encryptedMessage, index) => { try { if (encryptedMessage.length < sodiumNative.crypto_secretbox_NONCEBYTES + sodiumNative.crypto_secretbox_MACBYTES) { throw new Error('Invalid encrypted message length'); } const nonce = encryptedMessage.slice(0, sodiumNative.crypto_secretbox_NONCEBYTES); const ciphertext = encryptedMessage.slice(sodiumNative.crypto_secretbox_NONCEBYTES); const message = Buffer.allocUnsafe(ciphertext.length - sodiumNative.crypto_secretbox_MACBYTES); if (!sodiumNative.crypto_secretbox_open_easy(message, ciphertext, nonce, key)) { throw new Error('Decryption failed'); } results[index] = message; } catch (error) { results[index] = Buffer.from(''); } })); return results; } }; exports.CryptoService = CryptoService; exports.CryptoService = CryptoService = __decorate([ (0, common_1.Injectable)(), __metadata("design:paramtypes", [key_provider_1.KeyProvider, config_1.ConfigService]) ], CryptoService); //# sourceMappingURL=crypto.service.js.map