/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
var macTest = {

  /**
   * Verifies a MAC that was generated using Java and checks if the
   * verification was true.
   *
   * @param {String}
   *            macB64 the MAC, in Base64 encoded format.
   * @param {String}
   *            secretKeyB64 the secret key, in Base64 encoded format.
   * @param {String}
   *            dataB64 the data used to generate the MAC, in Base64 encoded
   *            format.
   * @throws {Error}
   *             if the MAC verification operation fails or the verification
   *             is false.
   */
  verify: function(macB64, secretKeyB64, dataB64) {

    'use strict';

    var errorData = {};
    errorData['MAC to verify (Base64 encoded) [Java]'] = macB64;
    errorData['Secret key (Base64 encoded) [Java]'] = secretKeyB64;
    errorData['Data used to generate MAC (Base64 encoded) [Java]'] = dataB64;

    try {
      cryptolib('symmetric.service', function(box) {
        var verified =
            box.symmetric.service.verifyMac(macB64, secretKeyB64, [dataB64]);

        if (!verified) {
          throw 'Verification of MAC was false.';
        }
      });
    } catch (error) {
      throw testUtils.serializeError(error, errorData);
    }
  },

  /**
   * Generates a MAC that will be verified using Java.
   *
   * @param {String}
   *            secretKeyB64 the secret key, in Base64 encoded format.
   * @param {String}
   *            dataB64 the data from which to generate the MAC, in Base64
   *            encoded format.
   * @returns {String} the generated MAC, in Base64 encoded format.
   * @throws {Error}
   *             if the MAC generation operation fails.
   */
  generate: function(secretKeyB64, dataB64) {

    'use strict';

    var errorData = {};
    errorData['Secret key (Base64 encoded) [Java]'] = secretKeyB64;
    errorData['Data to generate MAC (Base64 encoded) [Java]'] = dataB64;

    try {
      var macB64;
      cryptolib('symmetric.service', function(box) {
        macB64 = box.symmetric.service.getMac(secretKeyB64, [dataB64]);
      });

      return macB64;
    } catch (error) {
      throw testUtils.serializeError(error, errorData);
    }
  }
};