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

  /**
   * Asymmetrically decrypts some data that was encrypted using Java and
   * checks if the original data could be retrieved.
   *
   * @param {String}
   *            privateKeyPem the private key, in PEM format.
   * @param {String}
   *            encryptedDataB64 the encrypted data, in Base64 encoded format.
   * @param {String}
   *            dataB64 the data that was encrypted, in Base64 encoded format.
   * @throws {Error}
   *             if the decryption operation fails or the original data could
   *             not be retrieved.
   */
  decrypt: function(privateKeyPem, encryptedDataB64, dataB64) {

    'use strict';

    var errorData = {};
    errorData['Private key (PEM format) [Java]'] = privateKeyPem;
    errorData['Encrypted data (Base64 encoded) [Java]'] = encryptedDataB64;
    errorData['Data that was encrypted (Base64 encoded) [Java]'] = dataB64;

    try {
      cryptolib('asymmetric.service', function(box) {
        var decryptedDataB64 =
            box.asymmetric.service.decrypt(privateKeyPem, encryptedDataB64);

        if (decryptedDataB64 !== dataB64) {
          errorData['Decrypted data (Base64 encoded) [JS]'] = decryptedDataB64;

          throw 'Expected decrypted data (Base64 encoded): ' + dataB64 +
              ' ; Found: ' + decryptedDataB64;
        }
      });
    } catch (error) {
      throw testUtils.serializeError(error, errorData);
    }
  },

  /**
   * Asymmetrically encrypts some data that will be decrypted using Java.
   *
   * @param {String}
   *            publicKeyPem the public key, in PEM format.
   * @param {String}
   *            dataB64 the data to encrypt, in Base64 encoded format.
   * @returns {String} the asymmetrically encrypted data, in Base64 encoded
   *          format.
   * @throws {Error}
   *             if the encryption operation fails.
   */
  encrypt: function(publicKeyPem, dataB64) {

    'use strict';

    var errorData = {};
    errorData['Public key (PEM format) [Java]'] = publicKeyPem;
    errorData['Data to encrypt (Base64 encoded) [Java]'] = dataB64;

    try {
      var encryptedDataB64;
      cryptolib('asymmetric.service', function(box) {
        encryptedDataB64 =
            box.asymmetric.service.encrypt(publicKeyPem, dataB64);
      });

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