Cost of Encryption

Benchmark created on


Setup

// Input data for testing
const testData = {
  name: "John Doe",
  age: 30,
  email: "johndoe@example.com",
  address: {
    city: "New York",
    country: "USA"
  }
};

Teardown


Test runner

Ready to run.

Testing in
TestOps/sec
Unencrypted
// Test Case 1: JSON.stringify and JSON.parse a string
function testJSONStringifyAndParse(inputObj) {
  const jsonString = JSON.stringify(inputObj);
  const parsedObj = JSON.parse(jsonString);
  return parsedObj;
}

// Run the test
testJSONStringifyAndParse(testData);
ready
Encrypted
// Test Case 2: Encrypt, JSON.stringify, Decrypt, and then JSON.parse
async function testEncryptStringifyDecryptParse(inputObj) {
  // Function to convert an ArrayBuffer to a hex string
  function arrayBufferToHexString(buffer) {
    return Array.from(new Uint8Array(buffer))
      .map(byte => byte.toString(16).padStart(2, '0'))
      .join('');
  }

  // Function to convert a hex string to an ArrayBuffer
  function hexStringToArrayBuffer(hexString) {
    const bytes = new Uint8Array(hexString.match(/[\da-f]{2}/gi).map(h => parseInt(h, 16)));
    return bytes.buffer;
  }

  // Generate a random initialization vector (IV)
  const iv = window.crypto.getRandomValues(new Uint8Array(16));

  // Convert the input object to a JSON string
  const jsonString = JSON.stringify(inputObj);

  // Convert the JSON string to an ArrayBuffer
  const textEncoder = new TextEncoder();
  const data = textEncoder.encode(jsonString);

  // Encrypt the data using WebCrypto API (SHA-256)
  const key = await window.crypto.subtle.generateKey(
    { name: 'AES-CBC', length: 256 },
    true,
    ['encrypt', 'decrypt']
  );

  const encryptedData = await window.crypto.subtle.encrypt(
    { name: 'AES-CBC', iv },
    key,
    data
  );

  // Convert the encrypted data to a hex string
  const encryptedHexString = arrayBufferToHexString(encryptedData);

  // Decrypt the data using WebCrypto API
  const decryptedData = await window.crypto.subtle.decrypt(
    { name: 'AES-CBC', iv },
    key,
    hexStringToArrayBuffer(encryptedHexString)
  );

  // Convert the decrypted ArrayBuffer back to a JSON string
  const decryptedString = textEncoder.decode(decryptedData);

  // Parse the JSON string and return the parsed object
  return JSON.parse(decryptedString);
}

// Run the test
testEncryptStringifyDecryptParse(testData);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.