UNPKG

@signumjs/crypto

Version:

Cryptographic functions for building Signum Network apps.

80 lines 2.97 kB
"use strict"; /** * Original work Copyright (c) 2018 PoC-Consortium * Modified work Copyright (c) 2019 Burst Apps Team * Modified work Copyright (c) 2024 Signum Network */ Object.defineProperty(exports, "__esModule", { value: true }); exports.encryptData = encryptData; exports.encryptMessage = encryptMessage; const base_1 = require("./base"); const deflate_1 = require("pako/lib/deflate"); const random_1 = require("./random"); const cryptoError_1 = require("./typings/cryptoError"); /** * * @ignore * @internal */ async function encrypt(plaintext, nonce, sharedKeyOrig) { try { const sharedKey = new Uint8Array(sharedKeyOrig.slice(0)); for (let i = 0; i < base_1.CryptoParams.SharedKeyLength; i++) { sharedKey[i] ^= nonce[i]; } const adapter = base_1.Crypto.adapter; const key = adapter.sha256(sharedKey); return await adapter.encryptAes256Cbc(plaintext, key); } catch (e) { // @ts-ignore throw new cryptoError_1.CryptoError(e.message); } } /** * Encrypts arbitrary data for P2P message/data exchange using asymmetric encryption * * @see {@link decryptData} * @param plaintext Data to be encrypted * @param recipientPublicKeyHex The recipients public key in hexadecimal format * @param senderPrivateKeyHex The senders private (agreement) key hexadecimal format * @return The encrypted Data * * @category en/decryption */ async function encryptData(plaintext, recipientPublicKeyHex, senderPrivateKeyHex) { try { const sharedKey = base_1.ECKCDSA.sharedkey(base_1.Buffer.from(senderPrivateKeyHex, 'hex'), base_1.Buffer.from(recipientPublicKeyHex, 'hex')); const compressedData = (0, deflate_1.deflate)(plaintext); const nonce = (0, random_1.getRandomBytes)(base_1.CryptoParams.SharedKeyLength); const data = await encrypt(compressedData, nonce, sharedKey); return { nonce, data }; } catch (e) { // @ts-ignore throw new cryptoError_1.CryptoError(e.message); } } /** * Encrypts arbitrary message (UTF-8 compatible) for P2P message/data exchange using asymmetric encryption * @see {@link decryptMessage} * @param plaintext Message to be encrypted * @param recipientPublicKeyHex The recipients public key hexadecimal format * @param senderPrivateKeyHex The senders private (agreement) key hexadecimal format * @return The encrypted Message * * @category en/decryption */ async function encryptMessage(plaintext, recipientPublicKeyHex, senderPrivateKeyHex) { const data = new Uint8Array(base_1.Buffer.from(plaintext, 'utf-8')); const encryptedData = await encryptData(data, recipientPublicKeyHex, senderPrivateKeyHex); return { data: base_1.Buffer.from(encryptedData.data).toString('hex'), nonce: base_1.Buffer.from(encryptedData.nonce).toString('hex'), isText: true, }; } //# sourceMappingURL=encrypt.js.map