React Native

cryptoUtil

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

The secret sharing library is forked from secrets.js-grempe, with slight modifications for react native. The source code is provided in the bottom of this page.

import { RSA, KeyPair } from 'react-native-rsa-native';
import { NativeModules } from 'react-native';
import type { Aes as AesType } from 'react-native-aes-crypto';
import { encode as btoa } from 'base-64';
import { toByteArray, fromByteArray } from 'base64-js';
import * as sss from './secrets.js';

const Aes: any = NativeModules.Aes;
const EPHEMERAL_KEY_SIZE = 16;
const BITS = '8';

export async function split(
  secret: string,
  numShare: number,
  threshold: number,
): Promise<string[]> {
  return (await sss.split(secret, numShare, threshold)).map(share => share.substring(1));
}

export function combine(shares: string[]): string {
  return sss.combine(shares.map(share => BITS + share));
}

export interface SymCiphertext {
  ciphertext: string;
  iv: string;
}

export interface HybridCiphertext {
  encryptedMessage: SymCiphertext;
  encryptedEphemeralKey: string;
}

export function randomBytes(length: number): Promise<string> {
  return Aes.randomKey(length);
}

function generateRsaKeyPair(keySize: number = 4096): Promise<KeyPair> {
  return RSA.generateKeys(keySize);
}

export function generateEncryptionKeyPair(
  options: { type: 'rsa'; keySize: number } = { type: 'rsa', keySize: 4096 },
): Promise<KeyPair> {
  if (options.type === 'rsa') {
    return generateRsaKeyPair(options.keySize);
  }
  throw new Error(`Unsupported type ${options.type}`);
}

export function generateSigningKeyPair(
  options: { type: 'rsa'; keySize: number } = { type: 'rsa', keySize: 4096 },
): Promise<KeyPair> {
  return generateEncryptionKeyPair(options);
}

export async function encryptSym(
  data: string,
  symKey: string,
  algorithm: AesType.Algorithms = 'aes-128-cbc',
) {
  const iv = await Aes.randomKey(16);
  const ciphertext = await Aes.encrypt(data, symKey, iv, algorithm);
  return {
    ciphertext,
    iv: hexToBase64(iv),
  };
}

export function decryptSym(
  ciphertext: SymCiphertext,
  symKey: string,
  algorithm: AesType.Algorithms = 'aes-128-cbc',
): Promise<string> {
  const iv = base64ToHex(ciphertext.iv);
  return Aes.decrypt(ciphertext.ciphertext, symKey, iv, algorithm);
}

export async function encryptAsym(
  data: string,
  encKey: string,
): Promise<string | HybridCiphertext> {
  try {
    return await RSA.encrypt64(data, encKey);
  } catch (err: unknown) {
    // if error indicates plaintext too big
    // 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);
  }
}

export function decryptAsym(
  ciphertext: string | HybridCiphertext,
  decKey: string,
): Promise<string> {
  if (typeof ciphertext === 'string') {
    return RSA.decrypt64(ciphertext, decKey);
  }
  return decryptHybrid(ciphertext, decKey);
}

export async function encryptHybrid(
  data: string,
  encKey: string,
): Promise<HybridCiphertext> {
  const ephemeralKey = await Aes.randomKey(EPHEMERAL_KEY_SIZE);
  const encryptedMessage = await encryptSym(data, ephemeralKey);
  const encryptedEphemeralKey = await encryptAsym(ephemeralKey, encKey);
  if (typeof encryptedEphemeralKey !== 'string') {
    throw new Error(
      'Ephemeral key size is too large for the encryption key type',
    );
  }
  // encryptedEphemeralKey must be returned by crypto.publicEncrypt, i.e. a Uint8Array
  return { encryptedMessage, encryptedEphemeralKey };
}

export async function decryptHybrid(
  ciphertext: HybridCiphertext,
  decKey: string,
): Promise<string> {
  const { encryptedEphemeralKey } = ciphertext;
  const ephemeralKey = await decryptAsym(encryptedEphemeralKey, decKey);
  const { encryptedMessage } = ciphertext;
  return decryptSym(encryptedMessage, ephemeralKey);
}

export function sign(data: string, signingKey: string): Promise<string> {
  return RSA.sign(data, signingKey);
}

export function verify(
  data: string,
  verificationKey: string,
  signature: string,
): Promise<boolean> {
  return RSA.verify(signature, data, verificationKey);
}

export function hash(...data: string[]): Promise<string> {
  return Aes.sha256(data.join(''));
}

export function xor(a: string, b: string): string {
  const bChunks = split2(b);
  return split2(a)
    .map((byteHex, i) =>
      // eslint-disable-next-line no-bitwise
      (parseInt(byteHex, 16) ^ parseInt(bChunks[i], 16))
        .toString(16)
        .padStart(2, '0'),
    )
    .join('');
}

function split2(str: string): string[] {
  const chunks = str.match(/\w{2}/g);
  if (chunks === null) {
    throw new Error('Invalid encoding');
  }
  return chunks;
}

export function hexToBase64(hex: string): string {
  const chunks = split2(hex);
  return btoa(
    chunks.map(byteHex => String.fromCharCode(parseInt(byteHex, 16))).join(''),
  );
}

export function base64ToHex(b64: string): string {
  return binToHex(toByteArray(b64));
}

export function hexToBin(hex: string): Uint8Array {
  const chunks = split2(hex);
  return Uint8Array.from(chunks.map(byteHex => parseInt(byteHex, 16)));
}

export function binToHex(bin: Uint8Array): string {
  return bin.reduce(
    (str, byte) => str + byte.toString(16).padStart(2, '0'),
    '',
  );
}

export { toByteArray as base64ToBin, fromByteArray as BinToBase64 };

export function hexToUtf8(hex: string): string {
  return sss.hex2str(hex);
}

export function utf8ToHex(a: string): string {
  return sss.str2hex(a);
}

export function binToUtf8(bin: Uint8Array): string {
  return String.fromCharCode(...bin);
}

export function utf8ToBin(a: string): Uint8Array {
  return Uint8Array.from(a.split('').map(byte => byte.charCodeAt(0)));
}

export function base64ToUtf8(b64: string): string {
  return binToUtf8(toByteArray(b64));
}

export function utf8ToBase64(a: string): string {
  return fromByteArray(utf8ToBin(a));
}
  • EPHEMERAL_KEY_SIZE (global variable): is the number of random bytes of the ephemeral keys used in a hybrid (symmetric & asymmetric) encryption.

  • randomBytes (function): generates random bytes encoded in hexidecimal.

  • generateEncryptionKeyPair (function): generates fresh encryption key pairs.

  • generateSigningKeyPair (function): generates fresh signing key pairs.

  • 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: RSA

  • 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: RSA

  • 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 SHA512;

  • 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 SHA512.

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

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

  • hexToBase64 (function): transforms the encoding of binary data from hexidecimal to base64

  • base64ToHex (function): transforms the encoding of binary data from base64 to hexidecimal

  • hexToBin (function): decodes a hexidecimal-encoded string to a Uint8Array

  • binToHex (function): encodes a Uint8Array to hexidecimal

  • base64ToBin (function): decodes a base64-encoded string to a Uint8Array

  • binToBase64 (function): encodes a Uint8Array to base64

Encrypting

An Encryption is a JSON object that 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
import {randomBytes, hash} from './cryptoUtil';

const token: string = await randomBytes(16); // 'd1fbe8b5f3ffd7a16a2aa400ebc0194f'
const tokenHash: string = await hash(token); // '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
import {randomBytes, encryptSym} from './cryptoUtil';

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

const k: string = await randomBytes(16);
const c: string = await encryptSym(data, k);

With c, the ciphertext can be created like this:

// create-ciphertext-second-step.js
import {sign, encryptHybrid, SymCiphertext, HybridCiphertext} from './cryptoUtil';

const c: SymCiphertext = /* from create-ciphertext-first-step.js */;
const encryptorSigningKey: string = /* from some keystore */;
const decryptorEncryptionKey: string = /* from some keystore */;
const payload: string = JSON.stringify(c);
const signature: string = await crypto.sign(payload, encryptorSigningKey);
const signedPayload: string = JSON.stringify({payload, signature});

const ciphertext: HybridCiphertext = await encryptHybrid(signedPayload, decryptorEncryptionKey);

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.

import {
  split,
  hexToBase64,
  hexToUtf8,
  encryptAsym,
  isHybridCiphertext,
  hash,
  Shares } from './cryptoUtil';

type TrusteeShares = {
  [trusteeId: string]: {
    encrypted: string,
    hashed: string,
  },
};

async function createTrusteeShares(maskedSymKey: string, trustees: Object, trusteeThreshold: number): Promise<TrusteeShares> {
  const n = Object.keys(trustees).length;
  const shares: Shares = await split(maskedSymKey, n, trusteeThreshold);
  const trusteeShares: TrusteeShares = {};
  for (const [i, [trusteeId, {encryptionKey}]] of Object.entries(trustees).entries()) {
    const shareBase64 = hexToBase64(shares[i]);
    const shareUtf8 = hexToUtf8(shares[i]);
    const encryptedShare = await encryptAsym(shareBase64, encryptionKey);
    if (isHybridCiphertext(encryptedShare)) {
      throw new Error('share is too large');
    }
    const hashedShare = await hash(shareUtf8);
    trusteeShares[trusteeId] = {
      encrypted: encryptedShare,
      hashed: hashedShare,
    };
  }
  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 = await 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.

import {
  split,
  hexToBase64,
  hexToUtf8,
  encryptHybrid,
  utf8ToHex,
  hash,
  Shares } from './cryptoUtil';

type ValidatorShares = {
  [validatorId: string]: {
    encrypted: string,
  },
};

async function createValidatorShares(RAndBvkPayload: string, validators: Object, validatorThreshold: number): Promise<ValidatorShares> {
  const nPrime = Object.keys(validators).length;
  const shares: Shares = await split(RAndBvkPayload, nPrime, validatorThreshold);
  const validatorShares: ValidatorShares = {};
  for (const [i, [validatorId, {encryptionKey}]] of Object.entries(validators).entries()) {
    const shareBase64 = hexToBase64(shares[i]);
    const encryptedShare = await encryptHybrid(shareBase64, encryptionKey);
    validatorShares[validatorId] = {
      encrypted: encryptedShare,
    };
  }
  return validatorShares;
}

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

const RAndBvkJson = {
  mask: hexToBase64(R),
  decryptorIdentity: bvk,
};
const RAndBvkPayload = utf8ToHex(JSON.stringify(RAndBvkJson));

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

const validatorShares = await 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
import {generateSigningKeyPair} from './cryptoUtil';

const {private: channelSigningKey, public: channelKey} = await generateSigningKeyPair();

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.

import {sign} from './cryptoUtil';

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

const encryptionPayload = JSON.stringify(newEncryption);
const signature = await sign(encryptionPayload, channelSigningKey);

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 */
// Work in progress

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 */
import {decryptHybrid, verify, HybridCiphertext, SymCiphertext} from './cryptoUtil';

function decryptVerifyCiphertext(ciphertext: HybridCiphertext, decryptorDecryptionKey: string, encryptorVerificationKey: string): SymCiphertext {
  const decrypted = decryptHybrid(ciphertext, decryptorDecryptionKey);
  const {payload, signature} = JSON.parse(decrypted);
  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 = /* from some key store */;
const encryptorVerificationKey = /* from some key store */;

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 */
import {base64ToHex, combine} from './cryptoUtil';

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

Reconstructing the mask from validators

/* resconstruct-r.js */
import {base64ToHex, hexToUtf8, combine} from './cryptoUtil';

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

Decrypting!

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

import {xor, decryptSym} from './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);
const {token, secret} = dataJson;
if (token !== /* token */) {
  throw new Error('Token mismatch');
}
console.log(secret); // my_secret

Last updated