UNPKG

@signumjs/crypto

Version:

Cryptographic functions for building Signum Network apps.

77 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.decryptData = decryptData; exports.decryptMessage = decryptMessage; const inflate_1 = require("pako/lib/inflate"); const base_1 = require("./base"); const cryptoError_1 = require("./typings/cryptoError"); /** * * @ignore * @internal * */ async function decrypt(ivCiphertext, nonce, sharedKeyOrig) { if (ivCiphertext.length < base_1.CryptoParams.IvLength || ivCiphertext.length % base_1.CryptoParams.IvLength !== 0) { throw new cryptoError_1.CryptoError('Invalid Ciphertext'); } const sharedKey = new Uint8Array(sharedKeyOrig.slice(0)); for (let i = 0; i < base_1.CryptoParams.SharedKeyLength; i++) { sharedKey[i] ^= nonce[i]; } try { const adapter = base_1.Crypto.adapter; const key = adapter.sha256(sharedKey); return await adapter.decryptAes256Cbc(ivCiphertext, key); } catch (e) { // @ts-ignore throw new cryptoError_1.CryptoError(e.message); } } /** * Decrypts an encrypted cipher text * @param encryptedData The encrypted data * @param senderPublicKeyHex The senders public key in hex format * @param recipientPrivateKeyHex The recipients private (agreement) key in hex format * @return The original plain text * * @category en/decryption */ async function decryptData(encryptedData, senderPublicKeyHex, recipientPrivateKeyHex) { try { const sharedKey = base_1.ECKCDSA.sharedkey(base_1.Buffer.from(recipientPrivateKeyHex, 'hex'), base_1.Buffer.from(senderPublicKeyHex, 'hex')); const compressedPlaintext = await decrypt(encryptedData.data, encryptedData.nonce, sharedKey); return (0, inflate_1.inflate)(compressedPlaintext); } catch (e) { // @ts-ignore throw new cryptoError_1.CryptoError(e.message); } } /** * Decrypts an encrypted Message * @param encryptedMessage The encrypted message * @param senderPublicKeyHex The senders public key in hex format * @param recipientPrivateKeyHex The recipients private (agreement) key in hex format * @return The original message * * @category en/decryption */ async function decryptMessage(encryptedMessage, senderPublicKeyHex, recipientPrivateKeyHex) { if (!encryptedMessage.isText) { throw new cryptoError_1.CryptoError('Encrypted message is marked as non-text. Use decryptData instead'); } const encryptedData = { data: new Uint8Array(base_1.Buffer.from(encryptedMessage.data, 'hex')), nonce: new Uint8Array(base_1.Buffer.from(encryptedMessage.nonce, 'hex')) }; const decryptedBytes = await decryptData(encryptedData, senderPublicKeyHex, recipientPrivateKeyHex); return base_1.Buffer.from(decryptedBytes).toString('utf-8'); } //# sourceMappingURL=decrypt.js.map