/*
 * 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 hashTest = {

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

    'use strict';

    var errorData = {};
    errorData['Hash expected (Base64 encoded) [Java]'] = hashB64;
    errorData['Data that was hashed (Base64 encoded) [Java]'] = dataB64;

    try {
      cryptolib('primitives.service', function(box) {
        var hashB64Found = box.primitives.service.getHash([dataB64]);

        if (hashB64Found !== hashB64) {
          errorData['Hash found (Base64 encoded) [JS]'] = hashB64Found;

          throw 'Expected hash (Base64 encoded): ' + hashB64 +
              ' ; Found: ' + hashB64Found;
        }
      });
    } catch (error) {
      throw testUtils.serializeError(error, errorData);
    }
  },

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

    'use strict';

    var errorData = {};
    errorData['Data to hash (Base64 encoded) [Java]'] = dataB64;

    try {
      var hashB64;
      cryptolib('primitives.service', function(box) {
        hashB64 = box.primitives.service.getHash([dataB64]);
      });

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