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

var cryptoPolicy = require('scytl-cryptopolicy');
var asymmetric = require('../lib/index');
var secureRandom = require('scytl-securerandom');
var codec = require('scytl-codec');
var forge = require('node-forge');

describe('The asymmetric cryptography service should be able to ...', function() {
  var PUBLIC_KEY_PEM =
      '-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAglypZU45bnf2opnRI+Y51VqouBpvDT33xIB/OtbwKzwVpi+JrjBFtfk33tE9t/dSRs79CK94HRhCWcOiLa2qWPrjeZ9SBiEyScrhIvRZVBF41zBgwQNuRvJCsKmAqlZaFNJDZxEP4repmlBn1CfVFmfrXmOKqwP5F7l9ZtucveRzsfmF1yVPFkW8TMuB3YqMiyymyqHlS8ujCsu5I8tpgPbwuxdMOY94fNhSXrYkY8IuX1g1zdq/Z1jluOaR/UqK4UpnbuJaH/F0VgDNiWh6cTD0DFGEk0b70i5wU4Q3L/S6XZQRvSuADoCbhwBKuFL5pW5n865oLVb5S3wuVdWaGwIDAQAB-----END PUBLIC KEY-----';
  var PRIVATE_KEY_PEM =
      '-----BEGIN RSA PRIVATE KEY-----MIIEowIBAAKCAQEAglypZU45bnf2opnRI+Y51VqouBpvDT33xIB/OtbwKzwVpi+JrjBFtfk33tE9t/dSRs79CK94HRhCWcOiLa2qWPrjeZ9SBiEyScrhIvRZVBF41zBgwQNuRvJCsKmAqlZaFNJDZxEP4repmlBn1CfVFmfrXmOKqwP5F7l9ZtucveRzsfmF1yVPFkW8TMuB3YqMiyymyqHlS8ujCsu5I8tpgPbwuxdMOY94fNhSXrYkY8IuX1g1zdq/Z1jluOaR/UqK4UpnbuJaH/F0VgDNiWh6cTD0DFGEk0b70i5wU4Q3L/S6XZQRvSuADoCbhwBKuFL5pW5n865oLVb5S3wuVdWaGwI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ogQVPOLELeUIGLu/hjsSdDKiFCxCUZ948+9NuG+DnpXDWzw//r8mPBRRGGsqFws5Aipp7yjQ3kRDCCzGelPCVhHyfmKqA+8ewXPulKS3/wIyHIvaXmsuAtTfurHtpRyzjKmCBK1Y6WQ3trIXvo7s-----END RSA PRIVATE KEY-----';

  var PUBLIC_KEY_1024_PEM =
      '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpIzTG+VAAO9tGCrqoiwJ7e3Hz2IY4Nhfvlh4ZevDje7WIqGMzg0Ewf5UBhCD1BuYklxsD/urdWH5wXT1m7tD70ZqPNjE4N6qnDmR38u0AND24p7WkT4AOCDG5hiRG5SDm6hp1vaLVEBRhUtdFb6z/m8og+6ygTIkspzesZ+RaRwIDAQAB-----END PUBLIC KEY-----';
  var PRIVATE_KEY_1024_PEM =
      '-----BEGIN RSA PRIVATE KEY-----MIICXAIBAAKBgQCpIzTG+VAAO9tGCrqoiwJ7e3Hz2IY4Nhfvlh4ZevDje7WIqGMzg0Ewf5UBhCD1BuYklxsD/urdWH5wXT1m7tD70ZqPNjE4N6qnDmR38u0AND24p7WkT4AOCDG5hiRG5SDm6hp1vaLVEBRhUtdFb6z/m8og+6ygTIkspzesZ+RaRwIDAQABAoGAQZKko3+ExJJwMHd4Zl9+VuFFDISlhKV0Ii7Q/I/tVERh3NlrnE0GuQa9fhj7rgM+tnDeyG3MIIRugKGlbIKqAlWep1jGqcLw5dUy0plppB2S93BLq4XZ406iL+KS3OlJhYR9J14VcMoJjN8lGY2MYX7ywx+q5gJrREu5vBS33AECQQDUkZZX7cwyVeaBiDabdGpNxy88fIlRg1bRn29p0PmmmHcRZa0VaQm3EjbrVzg9xhd46IuBh60GGMYl4GdxiXQpAkEAy7HzJqqR+CptThAWA64hwcwWmujdjmBAJ69Scg+ZX61dpmHNiphvdrpbpYu7b2yPCOI1NfkLUoRSmyd5DGao7wJAVJB2lxRrH7s8sFtYHg/6GmcbS5zfpCXz7ADZeedA6h3NgIZKjTH0Q3hjkMxp+2lK/TbGCQnIs5w3d+oGPQzJwQJBALaQ+ODYElp+FFfaHRERWlorRLt1KVa5t+aZwehPSOUzKnO8xw+Ijqa4YvneYpF8mDqbHJwSae58gNllKJ5PyOsCQHbdbSFj0aClSs0AP+jVbpzINxiObn0brcZni/UI3guldO7vZNbWyr3h8QORN5HTg4ov4a3V8V0jlWboBZRJpvw=-----END RSA PRIVATE KEY-----';

  var ASYMMETRIC_CIPHER_OAEP_POLICY = {
    algorithm: {
      name: cryptoPolicy.options.asymmetric.cipher.algorithm.RSA_OAEP.name,
      hashAlgorithm: cryptoPolicy.options.asymmetric.cipher.algorithm.RSA_OAEP
                         .hashAlgorithm.SHA256,
      maskGenerator: {
        name: cryptoPolicy.options.asymmetric.cipher.algorithm.RSA_OAEP
                  .maskGenerator.MGF1.name,
        hashAlgorithm: cryptoPolicy.options.asymmetric.cipher.algorithm.RSA_OAEP
                           .maskGenerator.MGF1.hashAlgorithm.SHA1
      }
    }
  };

  var ASYMMETRIC_CIPHER_KEM_POLICY = {
    algorithm: {
      name: cryptoPolicy.options.asymmetric.cipher.algorithm.RSA_KEM.name,
      secretKeyLengthBytes: cryptoPolicy.options.asymmetric.cipher.algorithm
                                .RSA_KEM.secretKeyLengthBytes.KL_16,
      ivLengthBytes: cryptoPolicy.options.asymmetric.cipher.algorithm.RSA_KEM
                         .ivLengthBytes.IVL_12,
      tagLengthBytes: cryptoPolicy.options.asymmetric.cipher.algorithm.RSA_KEM
                          .tagLengthBytes.TL_16,
      keyDeriver: {
        name: cryptoPolicy.options.asymmetric.cipher.algorithm.RSA_KEM
                  .keyDeriver.name.KDF1,
        hashAlgorithm: cryptoPolicy.options.asymmetric.cipher.algorithm.RSA_KEM
                           .keyDeriver.hashAlgorithm.SHA256,
      },
      symmetricCipher: cryptoPolicy.options.asymmetric.cipher.algorithm.RSA_KEM
                           .symmetricCipher.AES_GCM
    }
  };

  var ENCRYPTED_DATA_JAVA_B64 =
      'SuIt3oT4a98kF+7sReHLxYuVTV8GtspAUf2607aTIdnLkHrN5gYNNeXoOHuVXZtm2AneV165PsRtUpEapGtzaeWpNZS7rhnPU2JjQ26p0PkR0A6nXGX7sn7QlH8kJ/etN7wVilHNGRlM2nvgMpbIhue/X3+OQ6ROYavDfEs9XC8QCJxgD5CvkDJANzfNaybPdf4yZ+QFL90T4ZePEy/PZbIPtZMWIz8xTUkZs4SUbtfph+8tX4o+0b1lCBQlAeqegZQcycN0/JkgsQdRi5l02wrg0lDj4QMFzB9h3uBhzv3Wn4DlN9OQtHYMkPz/9MurRhHkqKJBSkBcTKawTmcA9Q==';

  var data_;
  var oaepPolicy_;
  var kemPolicy_;
  var asymmetricEncrypterKem_;
  var asymmetricDecrypterKem_;
  var asymmetricEncrypterOaep_;
  var asymmetricDecrypterOaep_;

  beforeAll(function() {
    data_ = codec.utf8Encode('Ox2fUJq1gAbX');

    oaepPolicy_ = cryptoPolicy.newInstance();
    oaepPolicy_.asymmetric.cipher = ASYMMETRIC_CIPHER_OAEP_POLICY;
    kemPolicy_ = cryptoPolicy.newInstance();
    kemPolicy_.asymmetric.cipher = ASYMMETRIC_CIPHER_KEM_POLICY;

    var service = asymmetric.newService({policy: kemPolicy_});

    asymmetricEncrypterKem_ = service.newEncrypter().init(PUBLIC_KEY_PEM);
    asymmetricDecrypterKem_ = service.newDecrypter().init(PRIVATE_KEY_PEM);

    service = asymmetric.newService({policy: oaepPolicy_});
    asymmetricEncrypterOaep_ = service.newEncrypter().init(PUBLIC_KEY_PEM);
    asymmetricDecrypterOaep_ = service.newDecrypter().init(PRIVATE_KEY_PEM);
  });

  describe(
      'create an asymmetric encrypter/decrypter pair that should be able to ..',
      function() {
        it('encrypt and decrypt some data using RSA-KEM and 1024-bit keys',
           function() {
             var publicKey = forge.pki.publicKeyFromPem(PUBLIC_KEY_1024_PEM);
             var privateKey = forge.pki.privateKeyFromPem(PRIVATE_KEY_1024_PEM);

             // confirm that the keys have the expected modulus size
             expect(publicKey.n.bitLength()).toBe(1024);
             expect(privateKey.n.bitLength()).toBe(1024);

             var service = asymmetric.newService({policy: kemPolicy_});
             var asymmetricEncrypterKem =
                 service.newEncrypter().init(PUBLIC_KEY_1024_PEM);
             var asymmetricDecrypterKem =
                 service.newDecrypter().init(PRIVATE_KEY_1024_PEM);

             // Encrypt data.
             var encryptedData = asymmetricEncrypterKem.encrypt(data_);
             var decryptedData = asymmetricDecrypterKem.decrypt(encryptedData);

             // Verify that data was successfully decrypted.
             expect(decryptedData).toEqual(data_);
           });

        it('encrypt and decrypt some data using RSA-KEM and 2048-bit keys',
           function() {
             // Encrypt data.
             var encryptedData = asymmetricEncrypterKem_.encrypt(data_);

             // Decrypt data.
             var decryptedData = asymmetricDecrypterKem_.decrypt(encryptedData);

             // Verify that data was successfully decrypted.
             expect(decryptedData).toEqual(data_);
           });

        it('encrypt and decrypt some randomly generated data, 512 bytes in size, using RSA-KEM and 2048-bit keys',
           function() {
             var srs = secureRandom.newService();
             var randomGenerator = srs.newRandomGenerator();
             var data = randomGenerator.nextBytes(512);

             // Encrypt data.
             var encryptedData = asymmetricEncrypterKem_.encrypt(data);

             // Decrypt data.
             var decryptedData = asymmetricDecrypterKem_.decrypt(encryptedData);

             // Verify that data was successfully decrypted.
             expect(decryptedData).toEqual(data);
           });

        it('encrypt and decrypt some data, using RSA-OAEP', function() {
          // Encrypt data.
          var encryptedData = asymmetricEncrypterOaep_.encrypt(data_);

          // Decrypt data.
          var decryptedData = asymmetricDecrypterOaep_.decrypt(encryptedData);

          // Verify that data was successfully decrypted.
          expect(decryptedData).toEqual(data_);
        });

        it('decrypt some data that was encrypted, using RSA-OEAP with Java',
           function() {
             // Decrypt data.
             var decryptedData = asymmetricDecrypterOaep_.decrypt(
                 codec.base64Decode(ENCRYPTED_DATA_JAVA_B64));

             // Verify that data was successfully decrypted.
             expect(decryptedData).toEqual(data_);
           });

        it('throw an error when being created, using the wrong cipher algorithm',
           function() {
             var policy = cryptoPolicy.newInstance();
             policy.asymmetric.cipher.algorithm.name = 'wrong cipher algorithm';
             var service = asymmetric.newService({policy: policy});

             expect(function() {
               service.newEncrypter();
             }).toThrow();

             expect(function() {
               service.newDecrypter();
             }).toThrow();
           });

        it('throw an error when being created, using RSA-KEM with the wrong key derivation function',
           function() {
             var kemPolicy = clone(kemPolicy_);
             kemPolicy.asymmetric.cipher.algorithm.keyDeriver.name =
                 'wrong RSA-KEM key derivation function';
             var service = asymmetric.newService({policy: kemPolicy});

             expect(function() {
               service.newEncrypter();
             }).toThrow();

             expect(function() {
               service.newDecrypter();
             }).toThrow();
           });

        it('throw an error when being created, using RSA-KEM with the wrong key derivation function hash algorithm',
           function() {
             var kemPolicy = clone(kemPolicy_);
             kemPolicy.asymmetric.cipher.algorithm.keyDeriver.hashAlgorithm =
                 'wrong RSA-KEM key derivation function hash algorithm';
             var service = asymmetric.newService({policy: kemPolicy});

             expect(function() {
               service.newEncrypter();
             }).toThrow();

             expect(function() {
               service.newDecrypter();
             }).toThrow();
           });

        it('throw an error when being created, using RSA-KEM with the wrong symmetric cipher algorithm',
           function() {
             var kemPolicy = clone(kemPolicy_);
             kemPolicy.asymmetric.cipher.algorithm.symmetricCipher =
                 'wrong RSA-KEM symmetric cipher algorithm';
             var service = asymmetric.newService({policy: kemPolicy});

             expect(function() {
               service.newEncrypter();
             }).toThrow();

             expect(function() {
               service.newDecrypter();
             }).toThrow();
           });

        it('throw an error when being created, using RSA-OAEP with the wrong hash algorithm',
           function() {
             var oaepPolicy = clone(oaepPolicy_);
             oaepPolicy.asymmetric.cipher.algorithm.hashAlgorithm =
                 'wrong RSA-OAEP hash algorithm';
             var service = asymmetric.newService({policy: oaepPolicy});

             expect(function() {
               service.newEncrypter();
             }).toThrow();

             expect(function() {
               service.newDecrypter();
             }).toThrow();
           });

        it('throw an error when being created, using RSA-OAEP with the wrong mask generation function',
           function() {
             var oaepPolicy = clone(oaepPolicy_);
             oaepPolicy.asymmetric.cipher.algorithm.maskGenerator.name =
                 'wrong RSA-OAEP mask generation function';
             var service = asymmetric.newService({policy: oaepPolicy});

             expect(function() {
               service.newEncrypter();
             }).toThrow();

             expect(function() {
               service.newDecrypter();
             }).toThrow();
           });

        it('throw an error when being created, using RSA-OAEP with the wrong mask generation function hash algorithm',
           function() {
             var oaepPolicy = clone(oaepPolicy_);
             oaepPolicy.asymmetric.cipher.algorithm.maskGenerator
                 .hashAlgorithm =
                 'wrong RSA-OAEP mask generation function hash algorithm';
             var service = asymmetric.newService({policy: oaepPolicy});

             expect(function() {
               service.newEncrypter();
             }).toThrow();

             expect(function() {
               service.newDecrypter();
             }).toThrow();
           });
      });

  function clone(object) {
    return JSON.parse(JSON.stringify(object));
  }
});
