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

  /**
   * Symmetrically decrypts some data that was encrypted using Java and checks
   * if the original data could be retrieved.
   *
   * @param {String}
   *            secretKeyB64 the secret key, in Base64 encoded 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(secretKeyB64, encryptedDataB64, dataB64) {

    'use strict';

    var errorData = {};
    errorData['Secret key (Base64 encoded) [Java]'] = secretKeyB64;
    errorData['Encrypted data (Base64 encoded) [Java]'] = encryptedDataB64;
    errorData['Data that was encrypted (Base64 encoded) [Java]'] = dataB64;

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

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

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

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

    'use strict';

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

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

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