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

  /**
   * Verifies the digital signature of an XML file that was signed using Java
   * and checks if the verification was true.
   *
   * @param {String}
   *            publicKeyPem the public key, in PEM format.
   * @param {String}
   *            signedXmlFileB64 the signed XML file, in Base64 encoded
   *            format.
   * @param {String}
   *            signatureParentNode the parent node where the signature is
   *            found in the signed file.
   * @throws {Error}
   *             if the signature verification operation fails or the
   *             verification is false.
   */
  verify: function(publicKeyPem, signedXmlFileB64, signatureParentNode) {

    'use strict';

    var errorData = {};
    errorData['Public Key (PEM format) [Java]'] = publicKeyPem;
    errorData['Signed XML file (Base64 encoded) [Java]'] = signedXmlFileB64;
    errorData['Signature parent node [Java]'] = signatureParentNode;

    try {
      cryptolib('asymmetric.service', function(box) {
        var publicKey = forge.pki.publicKeyFromPem(publicKeyPem);

        var signedXmlFile = _converters.base64Decode(signedXmlFileB64);

        var inStream = [signedXmlFile].join('\n');

        var verified = box.asymmetric.service.verifyXmlSignature(
            publicKey, inStream, signatureParentNode);

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