Node.js

cryptoUtil

In the following sections, we will use different cryptographic primitives to implement parts of the PAD protocol. Here we provide a cryptoUtil.js Node.js script with these cryptographic primitives. (Requires Node.js v14+)

// cryptoUtil.js
const crypto = require('crypto');

const EPHEMERAL_KEY_SIZE = 16;

/**
 * @typedef {Object} SymCiphertext
 * @property {string} ciphertext
 * @property {string} iv
 */
/**
 * @typedef {Object} HybridCiphertext
 * @property {SymCiphertext} encryptedMessage
 * @property {string} encryptedEphemeralKey
 */

/**
 * @param {object} options
 * @param {Object.<string, crypto.KeyObject>}
 */
exports.generateSigningKeyPair = (options={type: 'ec', namedCurve:'prime256v1'}) => {
  return crypto.generateKeyPairSync(options.type, options);
}

/**
 * @param {Buffer} data
 * @param {Buffer} symKey
 * @param {string} algorithm
 * @return {SymCiphertext}
 */
function encryptSym(data, symKey, algorithm='aes-128-cbc') {
  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipheriv(algorithm, symKey, iv);
  let ciphertext = cipher.update(data);
  ciphertext = Buffer.concat([ciphertext, cipher.final()]);
  return {
    ciphertext: ciphertext.toString('base64'),
    iv: iv.toString('base64'),
  };
}
exports.encryptSym = encryptSym;

/**
 * @param {SymCiphertext} ciphertext
 * @param {symKey} string
 * @param {string} algorithm
 * @return {Buffer}
 */
function decryptSym(ciphertext, symKey, algorithm) {
  const iv = Buffer.from(ciphertext.iv, 'base64');
  const decipher = crypto.createDecipheriv(algorithm, symKey, iv);
  let data = decipher.update(Buffer.from(ciphertext.ciphertext, 'base64'));
  data = Buffer.concat([data, decipher.final()]);
  return data;
}
exports.decryptSym = decryptSym;

/**
 * @param {Buffer} data
 * @param {crypto.KeyLike} encKey
 * @return {Buffer | HybridCiphertext} the ciphertext as a bytes string
 */
function encryptAsym(data, encKey) {
  try {
    return crypto.publicEncrypt(encKey, data);
  } catch (err) {
    if (err.code === 'ERR_OSSL_RSA_DATA_TOO_LARGE_FOR_KEY_SIZE') {
      // avoid infinite recursive calls
      if (data.length <= EPHEMERAL_KEY_SIZE) {
        throw new Error('Ephemeral key size is too large for the encryption key type');
      }
      return encryptHybrid(data, encKey);
    }
    throw err;
  }
}
exports.encryptAsym = encryptAsym;

/**
 * @param {Buffer | HybridCiphertext} ciphertext
 * @param {crypto.KeyLike} decKey
 * @return {Buffer}
 */
function decryptAsym(ciphertext, decKey) {
  if (Buffer.isBuffer(ciphertext)) {
    return crypto.privateDecrypt(decKey, ciphertext);
  }
  return decryptHybrid(ciphertext, decKey);
}
exports.decryptAsym = decryptAsym;

/**
 * @param {Buffer} data
 * @param {crypto.KeyLike} encKey
 * @return {HybridCiphertext}
 */
function encryptHybrid(data, encKey) {
  const ephemeralKey = crypto.randomBytes(EPHEMERAL_KEY_SIZE);
  const encryptedMessage = encryptSym(data, ephemeralKey);
  const encryptedEphemeralKey = encryptAsym(ephemeralKey, encKey).toString('base64');
  // encryptedEphemeralKey must be returned by crypto.publicEncrypt, i.e. a Buffer
  return { encryptedMessage, encryptedEphemeralKey };
}
exports.encryptHybrid = encryptHybrid;

/**
 * @param {HybridCiphertext} ciphertext
 * @param {crypto.KeyLike} decKey
 * @return {Buffer}
 */
function decryptHybrid(ciphertext, decKey) {
  const encryptedEphemeralKey = Buffer.from(ciphertext.encryptedEphemeralKey, 'base64');
  const ephemeralKey = decryptAsym(encryptedEphemeralKey, decKey);
  const {encryptedMessage} = ciphertext;
  const data = decryptSym(encryptedMessage, ephemeralKey);
  return data;
}
exports.decryptHybrid = decryptHybrid;

/**
 * @param {string | Buffer} data
 * @param {crypto.KeyLike} signingKey
 * @param {string} algorithm
 * @return {Buffer}
 */
function sign(data, signingKey, algorithm='SHA256') {
  const sign = crypto.createSign(algorithm);
  sign.update(data);
  sign.end();
  const signature = sign.sign(signingKey);
  return signature;
}
exports.sign = sign;

/**
 * @param {string | Buffer} data
 * @param {crypto.KeyLike} verificationKey 
 * @param {string | Buffer} signature
 * @param {string} algorithm
 * @return {boolean}
 */
function verify(data, verificationKey, signature, algorithm='SHA256') {
  if (typeof signature === 'string') {
    signature = Buffer.from(signature, 'base64');
  }
  const verify = crypto.createVerify('SHA256');
  verify.update(data);
  verify.end();
  const verification = verify.verify(verificationKey, signature);
  return verification;
};
exports.verify = verify;

/**
 * @param {...(string | Buffer)} data
 * @return {Buffer}
 */
function hash(...data) {
  const sha256 = crypto.createHash('sha256');
  for (const d of data) {
    sha256.update(d);
  }
  return sha256.digest();
}
exports.hash = hash;

/**
 * @param {Buffer} a
 * @param {Buffer} b
 * @return {Buffer}
 */
function xor(a, b) {
  assert(a.length === b.length);
  const result = a.map((byte, i) => byte ^ b[i]);
  return Buffer.from(result);
}
exports.xor = xor;
  • EPHEMERAL_KEY_SIZE (global variable): is the number of random bytes of the ephemeral keys used in a hybrid (symmetric & asymmetric) encryption.

  • encryptSym (function): performs a symmetric encryption. Algorithm: AES-128-CBC.

  • decryptSym (function): performs a symmetric decryption. Algorithm: AES-128-CBC

  • encryptAsym (function): performs an asymmetric encryption. If the data to be encrypted is too large, it uses a hybrid encryption instead. Algorithm: depends on input key type

  • decryptAsym (function): performs an asymmetric decryption. If the ciphertext is a result from a hybrid encryption, then it uses hybrid decryption; Otherwise, it uses asymmetric decryption. Algorithm: depends on input key type

  • encryptHybrid (function): performs a hybrid encryption: performs a symmetric encryption on the data with an ephemeral key, then performs an asymmetric encryption on the ephemeral key with the encryption key.

  • decryptHybrid (function): performs a hybrid decryption: retrieve the ephemeral key with an asymmetric decryption. Then it performs a symmetric decryption on the payload with the ephemeral key.

  • sign (function): digitally signs a piece of data with a signing key. Algorithm: depends on input key type; data is first hashed with SHA256;

  • verify (function): verifies if a signature matches with the alleged data and verification key. Algorithm: depends on input key type; data is first hashed with SHA256.

  • hash (function): hashes the data in the argument list. Algorithm: SHA256

  • xor (function): performs exclusive-or on two binary arrays

Encrypting

An Encryption is a JSON object which has the following form:

{
    "description": string,
    "tokenHash": 256-bit-hex-string,
    "ciphertext": hybrid-ciphertext,
    "trusteeShares": {
        [trusteeId]: {
            "encrypted": base64-string,
            "hashed": 256-bit-hex-string,
        },
    },
    "validatorShares": {
        [validatorId]: {
            "encrypted": hybrid-ciphertext,
        },
    },
}

, where hybrid-ciphertext has the form

{
    "encryptedMessage": {
        "ciphertext": base64-string,
        "iv": base64-string,
    },
    "encryptedEphemeralKey": base64-string,
}

The encryption phase involves the encryptor sending an Encryption to the PAD server. Thus, it is essential to understand how it is created. We will go through its properties one by one.

  • "description": Description of the encryption. This can be an arbitrary string.

  • "tokenHash": Hased value of a token. tokenHash = SHA256(token).

  • "ciphertext": The ciphertext of the secret encrypted with the decryptor's public key and the symmetric key k.

  • "trusteeShares": A dictionary containing all the encrypted and hashed trustee shares.

    • [trusteeId]: A dictionary entry where the key is a trustee's ID, and the value is an object of encrypted and hashed trustee shares.

      • "encrypted": The trustee's share of the masked symmetric key k \oplus R used to encrypt the secret, encoded as a base64 string.

      • "hashed": SHA256 of the trustee's share, encoded as a hex string.

  • "validatorShares": A dictionary containing all the encrypted validator shares.

    • [validatorId]: A dictionary entry where the key is a validator's ID, and the value is an object of encrypted validator shares.

      • "encrypted": The validator's share of the mask R to the symmetric key used to encrypt the secret together with the decryptor's public key. Since the public key is large, the validator's shares are large too. Thus, the encryption of a validator's share uses an ephemeral key as a symmetric key. k and decryptor's key.

Creating token and tokenHash

A token is a random number sent from the encryptor to the decryptor for her to later request for a piece of encryptor's data. It is essential to keep it secret between the encryptor and decryptor until the data request phase. An encryption's ID is tokenHash, the hash value of token. For portability and readability, both token and tokenHash are represented as hexadecimal strings.

Important: note that token should be taken as a lowercase string when hashed into tokenHash.

// create-token-and-hash.js
const crypto = require('crypto');
const {hash} = require('./cryptoUtil');

const token = crypto.randomBytes(16).toString('hex'); // 'd1fbe8b5f3ffd7a16a2aa400ebc0194f'
const tokenHash = hash(token).toString('hex'); // '5892a6c7ad71b358df760b4291a8adf974f77bd9d3f16c4fd38c58147e80f401'

Creating ciphertext

The ciphertext part of an encryption should be encrypted with the symmetric key first, then the decryptor's encryption key. To ensure integrity, a digital signature from the encryptor against the ciphertext in the first encryption should be attached before the second encryption. In general, the first step creates the ciphertext c=SymEnck(token,s)c = SymEnc_{k}(token, s) Then the second step creates AsymEncBek(c,SignAsk(c))AsymEnc_{Bek}(c, Sign_{Ask}(c)) For example, suppose secret = "my_secret" is the encryptor's secret, the following code snippet generates c.

// create-ciphertext-first-step.js
const crypto = require('crypto');
const {encryptSym} = require('./cryptoUtil');

const token = /* from create-token-and-hash.js */;
const secret = 'my_secret';
const dataJson = {token, secret};
const data = JSON.stringify(dataJson);

const k = crypto.randomBytes(16);
const c = encryptSym(data, k);

With c, the ciphertext can be created like this:

// create-ciphertext-second-step.js
const crypto = require('crypto');
const fs = require('fs');
const {encryptAsym} = require('./cryptoUtil');

const c = /* from create-ciphertext-first-step.js */;
const encryptorSigningKey = fs.readFileSync('/path/to/encryptor/signing-key.pem');
const decryptorEncryptionKey = fs.readFileSync('/path/to/decryptor/encryption-key.pem');
const payload = JSON.stringify(c);
const signature = sign(payload, encryptorSigningKey).toString('base64');
const signedPayloadString = JSON.stringify({payload, signature});
const signedPayload = Buffer.from(signedPayloadString);

const ciphertext = encryptHybrid(signedPayload, decryptorEncryptionKey);

Secret sharing

The essential part of creating trusteeShares and validatorShares is secret sharing. We use the library secrets.js-grempe. In PAD, we also support 1 to be the thresholds. Moreover, we assumed the number of trustees and validators in instances is at most 256, it suffices to use 8 bits for secret sharing indices.

// secret-sharing.js
const sss = require('secrets.js-grempe');

const BITS = '8';

/**
 * @param {Buffer} s
 * @param {number} n
 * @param {number} t
 * @return {Buffer[]}
 */
function split(s, n, t) {
  assert(n >= t);
  let sharesBytes;
  if (n === 1) {
    const id = Buffer.alloc(1,1);
    const prefix = Buffer.alloc(1,1);
    sharesBytes = [Buffer.concat([id, prefix, s])];
  } else {
    const sHex = s.toString('hex');
    const shares = sss.share(sHex, n, t);
    sharesBytes = shares.map((share) =>
      // remove 'bits' part with slice
      Buffer.from(share.slice(1), 'hex'),
    );
  }
  return sharesBytes;
}
exports.split = split;

/**
 * @param {Buffer[]} shares
 * @return {Buffer}
 */
function combine(shares) {
  const combinedHex = sss.combine(
    shares.map((share) => BITS + share.toString('hex')),
  );
  return Buffer.from(combinedHex, 'hex');
}
exports.combine = combine;

Creating trusteeShares

To create trusteeShares, the encryptor should first have knowledge about the settings of the instance, including the trustee threshold and the list of trustees referencing the instance (check out GET /metadata and GET /all-trustees/{trustee-id}. These information are also in one of the first few blocks on the ledger). The symmetric key k is then masked with a random number. This masked symmetric key is the secret shared among the trustees. After that, each share of trustees' is encrypted with their individual encryption key (the mapping between secret sharing index and trustee does not matter, but we recommend following the order in the instance's metadata. For example, trustee1 may hold a share of index 00 in an encryption, but hold another share of index 01 in another encryption). For auditing purposes, the hash of each share before encrypting should also be included, so that after a trustee post her share, consistency can be checked.

const crypto = require('crypto');
const {encryptAsym, hash, xor} = require('./cryptoUtil');
const {split} = require('./secret-sharing');

/**
 * @param {Buffer} maskedSymKey
 * @param {object} trustees
 * @param {number} trusteeThreshold
 * @return {object}
 */
function createTrusteeShares(maskedSymKey, trustees, trusteeThreshold) {
  const n = Object.keys(trustees).length;
  const shares = split(maskedSymKey, n, trusteeThreshold);
  const trusteeShares = {};
  for (const [i, [trustee, {encryptionKey}]] of Object.entries(trustees).entries()) {
    const encryptedShare = encryptAsym(shares[i], encryptionKey);
    const hashedShare = hash(shares[i]);
    trusteeShares[trustee] = {
      encrypted: encryptedShare.toString('base64'),
      hashed: hashedShare.toString('hex'),
    };
  }
  return trusteeShares;
}

const k = /* from create-ciphertext-first-step.js */;
const R = crypto.randomBytes(16);

// the masked symmetric key maskedK is the secret to be shared
const maskedK = xor(k, R);

const trustees = {
  'trustee1': {
    encryptionKey: /* trustee1's encryption key */,
  },
  'trustee2': {
    encryptionKey: /* trustee2's encryption key */,
  },
};
const trusteeThreshold = 2;
const trusteeShares = createTrusteeShares(maskedK, trustees, trusteeThreshold);

Creating validatorShares

This is similar to creating trusteeShares, except the secret shared among the validators is the mask R together with the decryptor's public key to identify him.

const crypto = require('crypto');
const {split} = require('./secret-sharing');

/**
 * @param {Buffer} RAndBvkPayload
 * @param {object} validators
 * @param {number} validatorThreshold
 * @return {object}
 */
function createValidatorShares(RAndBvkPayload, validators, validatorThreshold) {
  const nPrime = Object.keys(validators).length;
  const shares = split(RAndBvkPayload, nPrime, validatorThreshold);
  const validatorShares = {};
  for (const [i, [validator, {encryptionKey}]] of Object.entries(validators).entries()) {
    const encryptedShare = encryptHybrid(shares[i], encryptionKey);
    validatorShares[validator] = {
      encrypted: encryptedShare,
    };
  }
  return validatorShares;
}

const R = /* from create-trustee-shares.js */;
const bvk = /* decryptor's verification key or identity */;

const RAndBvkJson = {
  mask: R.toString("base64"),
  decryptorIdentity: bvk.toString(),
};
const RAndBvkPayload = Buffer.from(JSON.stringify(RAndBvkJson));

const validators = {
  'validator1': {
    encryptionKey: /* validator1's encryption key */,
  },
  'validator2': {
    encryptionKey: /* validator2's encryption key */,
  },
};
const validatorThreshold = 2;

const validatorShares = createValidatorShares(RAndBvkPayload, validators, validatorThreshold);

Creating channelKey

You will also need a signing key pair for creating the new channel. This ensures that only the encryptor can modify the Encryption object using endpoint for updating an Encryption in a channel.

This channel key pair should be generated freshly and must not be the key pair that identifies the encryptor. Only the public (verification) key is sent to the server. The encryptor should keep the private (signing) key so long as she would update the Encryption therein.

// generate-channel-key.js
const {generateSigningKeyPair} = require('./cryptoUtil');

const channelKeyPair = generateSigningKeyPair();
const channelSigningKey = channelKeyPair.privateKey;
const channelKey = channelKeyPair.publicKey.export({type: 'spki', format: 'pem'});

That's it! We have gone through the steps of creating a new channel. Recall that the encryption is being sent to the PAD service server and the token is then shared with the decryptor out-of-band. The encryption channel allows the encryptor to update the secret which is useful in some use cases.

Updating Encryption object

Using the channel signing key and the token-hash, the encryptor can update her Encryption object in the channel associated with the token. The following code snippets show how one create encryptionPayload and signature required for the operation.

const {sign} = require('./cryptoUtil');

const channelSigningKey = /* from generate-channel-key.js */
const newEncryption = {
  // the new encryption content...
};

const encryptionPayload = JSON.stringify(newEncryption);
const signatureBuffer = sign(encryptionPayload, channelSigningKey);
const signature = signatureBuffer.toString('base64');

Decrypting

The decryption phase happens after the encryption has been uploaded, a data request has been posted, and sufficient number of trustees and validators, respectivelly, have responded. At this stage, the decryptor has enough information to decrypt the encryptor's secret.

Verifying responses correctness

It is important for the decryptor to check correctness and integrity of the trustee and validator responses. Checking correctness can be done by checking consistency between a response and its hash submitted by the encryptor at encryption time. Checking integrity involves verifying a signature against the response payload.

/* verify-responses.js */
const {hash, verify} = require('./cryptoUtil');

/**
 * @typedef {Object} SignerMetadata
 * @property {string} id
 * @property {string} fullName
 * @property {'Trustee' | 'Validator' | 'Server'} role
 */ 
/**
 * @typedef {Object} SignedResponse
 * @property {string} payload
 * @property {{signerMetadata: SignerMetadata, payload: string}}
/**
 * @param {string} token
 * @param {Object<string, string>} trusteeVerificationKeys
 * @param {Object<string, SignedResponse>} trusteeResponses
 * @param {Object<string, string>} hashedTrusteeShares
 */
function verifyTrusteeResponses(token, trusteeVerificationKeys, trusteeResponses, hashedTrusteeShares) {
  for (const [trusteeId, signedTrusteeShare] of Object.entries(trusteeResponses)) {
    // check signature
    const trusteeResponsePayload = signedTrusteeShare.trusteeResponse;
    const vk = trusteeVerificationKeys[trusteeId];
    const signature = signedTrusteeShare.signature.payload;
    if (!verify(trusteeResponsePayload, vk, signature)) {
      throw new Error('Signature not match with payload');
    }

    const trusteeResponse = JSON.parse(trusteeResponsePayload);
    // check payload metadata
    if (trusteeResponse.token !== token) {
      throw new Error('Token mismatch');
    }
    if (trusteeResponse.type !== 'trustee_response') {
      throw new Error('Object type mismatch');
    }
    // check signer consistency
    const signer = signedTrusteeShare.signature.signerMetadata;
    if (signer.id !== trusteeId ||
      trusteeResponse.trusteeId !== trusteeId ||
      signer.role !== 'Trustee') {
      throw new Error('Wrong signer');
    }
    // check hash
    const {trusteeShare} = trusteeResponse;
    const hex = hash(Buffer.from(trusteeShare, 'base64')).toString('hex');
    if (hex !== hashedTrusteeShares[trusteeId]) {
      throw new Error('Wrong trustee share');
    }
  }
}

/**
 * @param {string} token
 * @param {Object<string, string>} validatorVerificationKeys
 * @param {Object<string, SignedResponse>} validatorResponses
 */
function verifyValidatorResponses(token, validatorVerificationKeys, validatorResponses) {
  for (const [validatorId, signedValidatorShare] of Object.entries(validatorResponses)) {
    // check signature
    const validatorResponsePayload = signedValidatorShare.validatorResponse;
    const vk = validatorVerificationKeys[validatorId];
    const signature = signedValidatorShare.signature.payload;
    if (!verify(validatorResponsePayload, vk, signature)) {
      throw new Error('Signature not match with payload');
    }

    const validatorResponse = JSON.parse(validatorResponsePayload);
    // check payload metadata
    if (validatorResponse.token !== token) {
      throw new Error('Token mismatch');
    }
    if (validatorResponse.type !== 'validator_response') {
      throw new Error('Object type mismatch');
    }
    // check signer consistency
    const signer = signedValidatorShare.signature.signerMetadata;
    if (signer.id !== validatorId ||
      validatorResponse.validatorId !== validatorId ||
      signer.role !== 'Validator') {
      throw new Error('Wrong signer');
    }
  }
}

const token = /* token */;
/* these verification keys can be cached/stored locally */
const trusteeVerificationKeys = {
  'trustee1': /* from GET /all-trustees/trustee1 */,
  /* ... */
};
const validatorVerificationKeys = {
  'validator1': /* from GET /all-validators/validator1 */,
  /* ... */
};
const {trusteeResponses} = /* from GET /data-requests/{token}/trustee-responses */;
/*
{
  "trustee100": {
    "payload": "{\"token\":\"e3b0c44298fc1c149afbf4c8996fb924\",\"trusteeShare\":\"0110\",\"type\":\"trustee_response\",\"trusteeId\":\"trustee100\"}",
    "signature": {
      "signerMetadata": {
        "id": "trustee100",
        "fullName": "Trustee-100",
        "role": "Trustee"
      },
      "payload": "MEUCIGUjs7m3ZaJxB7i9G2GjEI+LpkXcsed3fkVDdchB1W5WAiEAtUsM5m/ouA/eaJBk39DT0tDLc97TeM093s4vuws+fgc="
    },
    "submissionTime": "2021-09-13T11:42:50Z"
  }
}
*/
const {validatorResponses} = /* from GET /data-requests/{token}/validator-responses */;
const {hashedTrusteeShares} = /* from GET /encryptions/{token-hash}/hashed-trustee-shares */;
verifyTrusteeResponses(
  token,
  trusteeVerificationKeys,
  trusteeResponses,
  hashedTrusteeShares,
);
verifyValidatorResponses(
  token,
  validaotrVerificationKeys,
  validatorResponses,
);

Verifying ciphertext integrity

Recall that the ciphertext payload includes the encryptor's signature before encrypted with decryptor's encryption key. This ensures that the payload is not modified by third party, including the PAD server. The signature needs to be verified before decrypting.

/* verify-ciphertext.js */
const fs = require('fs');
const {decryptHybrid, verify} = require('./cryptoUtil');

/** @typedef {import ('crypto').KeyLike} KeyLike
/** @typedef {import ('./cryptoUtil').HybridCiphertext} HybridCiphertext
/** @typedef {import ('./cryptoUtil').SymCiphertext} SymCiphertext

/**
 * @param {HybridCiphertext} ciphertext
 * @param {KeyLike} decryptorDecryptionKey
 * @param {KeyLike} encryptorVerificationKey
 * @return {SymCiphertext}
 */
function decryptVerifyCiphertext(ciphertext, decryptorDecryptionKey, encryptorVerificationKey) {
  const decrypted = decryptHybrid(ciphertext, decryptorDecryptionKey);
  const signedPayloadString = decrypted.toString('utf8');
  const {payload, signature} = JSON.parse(signedPayloadString);
  if (!verify(payload, encryptorVerificationKey, signature)) {
    throw new Error('Signature not match with payload');
  }
  const innerCiphertext = JSON.parse(payload);
  return innerCiphertext;
}

const {ciphertext} = /* from GET /encryptions/{token-hash}/ciphertext */;
const decryptorDecryptionKey = fs.readFileSync('/path/to/decryptor/decryption-key.pem');
const encryptorVerificationKey = fs.readFileSync('/path/to/encryptor/verification-key.pem');

const c = decryptVerifyCiphertext(
  ciphertext,
  decryptorDecryptionKey,
  encryptorVerificationKey,
);

Reconstructing masked symmetric key from trustees

To perform the symmetric decryption we need sufficient responses from trustees and validators, respectively. Then those will combine to the masked symmetric key and the masked. We show how to reconstruct the masked symmetric key from trustees' responses in this section. Obviously, it has redundancy with our previous example. In actual implementation, these scripts can be merged. For example, parse the response, push the share to an array only if it is valid, then combine those later.

/* reconstruct-masked-k.js */
const {combine} = require('./secret-sharing.js');

const {trusteeResponses} = /* from GET /data-requests/{token}/trustee-responses */;
const trusteeShares = Object.values(trusteeResponses).map((signed) => {
  const trusteeResponse = JSON.parse(signed.trusteeResponse);
  const share = Buffer.from(trusteeResponse.trusteeShare, 'base64');
  return share;
});
const maskedK = combine(trusteeShares);

Reconstructing the mask from validators

/* resconstruct-r.js */
const {combine} = require('./secret-sharing.js');

const {validatorResponses} = /* from GET /data-requests/{token}/validator-responses */;
const validatorShares = Object.values(validatorResponses).map((signed) => {
  const validatorResponse = JSON.parse(signed.validatorResponse);
  const share = Buffer.from(validatorResponse.validatorShare, 'base64');
  return share;
});
const RAndBvkPayload = combine(validatorShares);
const RAndBvkString = RAndBvkPayload.toString();
const RAndBvkJson = JSON.parse(RAndBvkString);
const R = Buffer.from(RAndBvkJson.mask, 'base64');

Decrypting!

The decryptor now has everything to retrieve the encryptor's secret.

const {xor, decryptSym} = require('./cryptoUtil');

const maskedK = /* from reconstruct-masked-k.js */;
const R = /* from reconstruct-r.js */;
const c = /* from verify-ciphertext.js */;

const k = xor(maskedK, R);
const decrypted = decryptSym(c, k);
const dataJson = JSON.parse(decrypted.toString('utf8'));
const {token, secret} = dataJson;
if (token !== /* token */) {
  throw new Error('Token mismatch');
}
console.log(secret); // my_secret

Last updated