/*
 * 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
 */
/* jshint node:true */
'use strict';

var digitalEnvelope = require('../lib/index');
var cryptoPolicy = require('scytl-cryptopolicy');
var asymmetric = require('scytl-asymmetric');
var symmetric = require('scytl-symmetric');
var codec = require('scytl-codec');

describe('The digital envelope module should be able to ...', function() {
  var PUBLIC_KEY_PEMS = [
    '-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAglypZU45bnf2opnRI+Y51VqouBpvDT33xIB/OtbwKzwVpi+JrjBFtfk33tE9t/dSRs79CK94HRhCWcOiLa2qWPrjeZ9SBiEyScrhIvRZVBF41zBgwQNuRvJCsKmAqlZaFNJDZxEP4repmlBn1CfVFmfrXmOKqwP5F7l9ZtucveRzsfmF1yVPFkW8TMuB3YqMiyymyqHlS8ujCsu5I8tpgPbwuxdMOY94fNhSXrYkY8IuX1g1zdq/Z1jluOaR/UqK4UpnbuJaH/F0VgDNiWh6cTD0DFGEk0b70i5wU4Q3L/S6XZQRvSuADoCbhwBKuFL5pW5n865oLVb5S3wuVdWaGwIDAQAB-----END PUBLIC KEY-----',
    '-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAngCJ2RYh3XOvghmAi2MT26/fx4Hx8gYkYS2zaf9c2H8Qns1hnIHO8pIlHze/stUmNzim6nlytbJLQHmVDu64Pf9dn1ClAW2caKqUo4ofjnOzDd6RocQByjTsvZ1nOcG5BMYtOWGua+QIVFrxvxZgL6T3ShQ+9J3/1LiQDUmWj0kMoct6vRJuNkJxVFegtIEqYZYTTFI1+Y25k040NFu0e9IDwDXQA63EqKL3DjrgxdjOY+KXu4zU6DUcL4VcKaTMs1+pDfU6bSOtrecuasKkEmNE9fuy9WejFqNGqlrNVCeYmOOnNXvI0vCdH1bw4/CpqddxvGZOStczF8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02N9U+b02G0auPmBKM35LXO4YGhZep1Vig+MLycR8OSe0cd4gzk52u3Th9I3e0bV9Fw=-----END RSA PRIVATE KEY-----'
  ];
  var DATA = 'Ox2fUJq1gAbX';

  var envelopeService_;
  var envelopeGenerator_;
  var envelopeOpener_;
  var data_;

  beforeAll(function() {
    envelopeService_ = digitalEnvelope.newService();
    data_ = codec.utf8Encode(DATA);
  });

  beforeEach(function() {
    envelopeGenerator_ = envelopeService_.newGenerator().init(
        PUBLIC_KEY_PEMS[0], PUBLIC_KEY_PEMS[1]);
    envelopeOpener_ = envelopeService_.newOpener().init(PRIVATE_KEY_PEMS[0]);
  });

  describe('create a digital envelope service that should be able to ..', function() {
    describe('create a digital envelope generator/opener pair that should be able to', function() {
      it('generate a digital envelope with a single public key and open the envelope with the corresponding private key',
         function() {
           var envelope =
               envelopeGenerator_.init(PUBLIC_KEY_PEMS[0]).generate(data_);

           var retrievedData = envelopeOpener_.open(envelope);
           expect(retrievedData).toEqual(data_);
         });

      it('generate a digital envelope with multiple public keys and open the envelope with any corresponding private key',
         function() {
           var envelope = envelopeGenerator_.generate(data_);

           var retrievedData;
           for (var i = 0; i < PRIVATE_KEY_PEMS.length; i++) {
             retrievedData =
                 envelopeOpener_.init(PRIVATE_KEY_PEMS[i]).open(envelope);
             expect(retrievedData).toEqual(data_);
           }
         });

      it('generate and open a digital envelope, using a provided cryptographic policy',
         function() {
           var policy = cryptoPolicy.newInstance();
           policy.digitalEnvelope.symmetric.mac.hashAlgorithm =
               cryptoPolicy.options.digitalEnvelope.symmetric.mac.hashAlgorithm
                   .SHA512_224;

           var envelopeService = digitalEnvelope.newService({policy: policy});
           var envelopeGenerator =
               envelopeService.newGenerator().init(PUBLIC_KEY_PEMS[0]);
           var envelopeOpener =
               envelopeService.newOpener().init(PRIVATE_KEY_PEMS[0]);

           var envelope = envelopeGenerator.generate(data_);

           var mac = envelope.mac;
           expect(mac.length).toBe(28);

           var retrievedData = envelopeOpener.open(envelope);
           expect(retrievedData).toEqual(data_);
         });

      it('generate and open a digital envelope, using a provided symmetric cryptography service',
         function() {
           var envelopeService = digitalEnvelope.newService(
               {symmetricCryptographyService: symmetric.newService()});
           var envelopeGenerator =
               envelopeService.newGenerator().init(PUBLIC_KEY_PEMS[0]);
           var envelopeOpener =
               envelopeService.newOpener().init(PRIVATE_KEY_PEMS[0]);

           var envelope = envelopeGenerator.generate(data_);

           var retrievedData = envelopeOpener.open(envelope);
           expect(retrievedData).toEqual(data_);
         });

      it('generate and open a digital envelope, using a provided asymmetric cryptography service',
         function() {
           var envelopeService = digitalEnvelope.newService(
               {asymmetricCryptographyService: asymmetric.newService()});
           var envelopeGenerator =
               envelopeService.newGenerator().init(PUBLIC_KEY_PEMS[0]);
           var envelopeOpener =
               envelopeService.newOpener().init(PRIVATE_KEY_PEMS[0]);

           var envelope = envelopeGenerator.generate(data_);

           var retrievedData = envelopeOpener.open(envelope);
           expect(retrievedData).toEqual(data_);
         });

      it('open a digital envelope, generated with a single public key, that was recreated by the service from its components',
         function() {
           var envelope =
               envelopeGenerator_.init(PUBLIC_KEY_PEMS[0]).generate(data_);

           var newEnvelope = envelopeService_.newEnvelope(
               envelope.encryptedData, envelope.mac,
               envelope.encryptedSecretKeyPairs);

           var retrievedData = envelopeOpener_.open(newEnvelope);
           expect(retrievedData).toEqual(data_);
         });

      it('open a digital envelope, generated with multiple public keys, that was recreated by the service from its components',
         function() {
           var envelope = envelopeGenerator_.generate(data_);

           var newEnvelope = envelopeService_.newEnvelope(
               envelope.encryptedData, envelope.mac,
               envelope.encryptedSecretKeyPairs);

           var retrievedData = envelopeOpener_.open(newEnvelope);
           for (var i = 0; i < PRIVATE_KEY_PEMS.length; i++) {
             retrievedData =
                 envelopeOpener_.init(PRIVATE_KEY_PEMS[i]).open(newEnvelope);
             expect(retrievedData).toEqual(data_);
           }
         });

      it('open a digital envelope, generated with a single public key, that was serialized and deserialized',
         function() {
           var envelope =
               envelopeGenerator_.init(PUBLIC_KEY_PEMS[0]).generate(data_);

           var envelopeJson = envelope.toJson();
           var envelopeFromJson = envelopeService_.newEnvelope(envelopeJson);

           var retrievedData = envelopeOpener_.open(envelopeFromJson);
           expect(retrievedData).toEqual(data_);
         });

      it('open a digital envelope, generated with a multiple public keys, that was serialized and deserialized',
         function() {
           var envelope = envelopeGenerator_.generate(data_);

           var envelopeJson = envelope.toJson();
           var envelopeFromJson = envelopeService_.newEnvelope(envelopeJson);

           var retrievedData;
           for (var i = 0; i < PRIVATE_KEY_PEMS.length; i++) {
             retrievedData = envelopeOpener_.init(PRIVATE_KEY_PEMS[i])
                                 .open(envelopeFromJson);
             expect(retrievedData).toEqual(data_);
           }
         });

      it('throw an error when generating a digital envelope before the generator has been initialized with a public key',
         function() {
           var envelopeGenerator = envelopeService_.newGenerator();

           expect(function() {
             envelopeGenerator.generate(data_);
           }).toThrow();
         });

      it('throw an error when opening a digital envelope before the opener has been initialized with a private key',
         function() {
           var envelope = envelopeGenerator_.generate(data_);

           var envelopeOpener = envelopeService_.newOpener();

           expect(function() {
             envelopeOpener.open(envelope);
           }).toThrow();
         });

      it('throw an error when opening a digital envelope with the wrong private key',
         function() {
           var envelope =
               envelopeGenerator_.init(PUBLIC_KEY_PEMS[0]).generate(data_);
           expect(function() {
             envelopeOpener_.init(PRIVATE_KEY_PEMS[1]).open(envelope);
           }).toThrow();
         });

      it('throw an error when opening a corrupted digital envelope',
         function() {
           var envelope = envelopeGenerator_.generate(data_);
           var envelopeJson = envelope.toJson();

           var corruptedEnvelopeJson = envelopeJson.replace(
               '\"encryptedDataBase64\":\"', '\"encryptedDataBase64\":\"0');
           var corruptedEnvelope =
               envelopeService_.newEnvelope(corruptedEnvelopeJson);
           expect(function() {
             envelopeOpener_.open(corruptedEnvelope);
           }).toThrow();
         });
    });
  });
});
