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

  /**
   * Verifies the digital signature of some data that was signed using Java
   * and checks if the verification was true.
   *
   * @param {String}
   *            signatureB64 the signature to verify, in Base64 encoded format.
   * @param {String}
   *            publicKeyPem the public key, in PEM format.
   * @param {String}
   *            dataB64 the data that was signed, in Base64 encoded format.
   * @throws {Error}
   *             if the signature verification operation fails or the
   *             verification is false.
   */
  verify: function(signatureB64, publicKeyPem, dataB64) {

    'use strict';

    var errorData = {};
    errorData['Signature (Base64 encoded) [Java]'] = signatureB64;
    errorData['Public Key (PEM format) [Java]'] = publicKeyPem;
    errorData['Data that was signed (Base64 encoded) [Java]'] = dataB64;

    try {
      cryptolib('asymmetric.service', function(box) {
        var verified = box.asymmetric.service.verifySignature(
            signatureB64, publicKeyPem, [dataB64]);

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

  /**
   * Generates a digital signature that will be verified using Java.
   *
   * @param {String}
   *            privateKeyPem the private key, in PEM format.
   * @param {String}
   *            dataB64 the data to sign, in Base64 encoded format.
   * @returns {String} the digital signature, in Base64 encoded format.
   * @throws {Error}
   *             if the signature generation operation fails.
   */
  sign: function(privateKeyPem, dataB64) {

    'use strict';

    var errorData = {};
    errorData['Prvate key (PEM format) [Java]'] = privateKeyPem;
    errorData['Data to sign (Base64 encoded) [Java]'] = dataB64;

    try {
      var signatureB64;
      cryptolib('asymmetric.service', function(box) {
        signatureB64 = box.asymmetric.service.sign(privateKeyPem, [dataB64]);
      });

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