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

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

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/S6XZQRvSuADoCbhwBKuFL5pW5n865oLVb5S3wuVdWaGwIDAQABAoIBAC/tn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/hjsSdDKiFCxCUZ948+9NuG+DnpXDWzw//r8mPBRRGGsqFws5Aipp7yjQ3kRDCCzGelPCVhHyfmKqA+8ewXPulKS3/wIyHIvaXmsuAtTfurHtpRyzjKmCBK1Y6WQ3trIXvo7s-----END RSA PRIVATE KEY-----';

  var DATA_FROM_JAVA = 'This is a string from Java.';

  var signer_;
  var sigVerifier_;
  var policy_;
  var data_;
  var signature_;
  var invalidKeyPair_;

  beforeAll(function() {
    var service = asymmetric.newService();
    signer_ = service.newSigner().init(PRIVATE_KEY_PEM);
    sigVerifier_ = service.newSignatureVerifier().init(PUBLIC_KEY_PEM);
    policy_ = cryptoPolicy.newInstance();
    data_ = codec.utf8Encode('Ox2fUJq1gAbX');

    signature_ = signer_.sign(data_);

    policy_.asymmetric.keyPair.encryption.keyLengthBits = 128;
    policy_.asymmetric.keyPair.encryption.publicExponent = 1;
    service = asymmetric.newService({policy: policy_});
    var keyPairGenerator = service.newKeyPairGenerator();
    invalidKeyPair_ = keyPairGenerator.next();
  });

  beforeEach(function() {
    policy_ = cryptoPolicy.newInstance();
  });

  describe('create a signer/signature verifier pair that should be able to ..', function() {
    it('sign some data and verify the signature, using a specified secure random service object',
       function() {
         var service = asymmetric.newService(
             {secureRandomService: secureRandom.newService()});
         var signer = service.newSigner().init(PRIVATE_KEY_PEM);
         var sigVerifier = service.newSignatureVerifier().init(PUBLIC_KEY_PEM);

         var signature = signer.sign(data_);

         expect(sigVerifier.verify(signature, data_)).toBeTruthy();
       });

    it('sign some data and verify the signature, using RSA and SHA256',
       function() {
         var policy = cryptoPolicy.newInstance();
         policy.asymmetric.signer = {
           algorithm: 'RSA',
           hashAlgorithm: 'SHA256',
           publicExponent: 65537,
         };

         var service = asymmetric.newService({policy: policy});
         var signer = service.newSigner().init(PRIVATE_KEY_PEM);
         var sigVerifier = service.newSignatureVerifier().init(PUBLIC_KEY_PEM);

         var signature = signer.sign(data_);

         expect(sigVerifier.verify(signature, data_)).toBeTruthy();
       });

    it('sign some data and verify the signature, using RSA, SHA256 and RSA-PSS padding',
       function() {
         var policy = cryptoPolicy.newInstance();
         policy.asymmetric.signer = {
           algorithm: 'RSA',
           hashAlgorithm: 'SHA256',
           padding: {
             name: 'PSS',
             hashAlgorithm: 'SHA256',
             maskGenerator: {name: 'MGF1', hashAlgorithm: 'SHA256'},
             saltLengthBytes: 32
           },
           publicExponent: 65537,
         };

         var service = asymmetric.newService({policy: policy});
         var signer = service.newSigner().init(PRIVATE_KEY_PEM);
         var sigVerifier = service.newSignatureVerifier().init(PUBLIC_KEY_PEM);

         var signature = signer.sign(data_);

         expect(sigVerifier.verify(signature, data_)).toBeTruthy();
         expect(sigVerifier.verify(signature, codec.utf8Encode('')))
             .toBeFalsy();
       });

    it('sign an empty string and verify the signature, using SHA256 with RSA',
       function() {
         var data = codec.utf8Encode('');

         var signature = signer_.sign(data);

         expect(sigVerifier_.verify(signature, data)).toBeTruthy();
       });

    it('verify a signature that was generated using Java', function() {
      // Signature generated using Java.
      var signatureB64 =
          'KuQPmBRE/JpNQ5mvh1Y1LvW3Jr/ZYlYqOgdbgXLVZp+gjVtXHDgFZzIrC8+S+VdTs9WINjxN8aIZlbiemZ+YvXZ7fDOoJsZJRboyrFN9VGz6sWWVXAv28Xj1a2lPNlys8dO3uY0s5R77kDCvBHV4nJh0Hq2Ry+JRjRcrlPsIiDWzm9iTY7V6XzkVGCo58qWyQtloC0s73i8UM6V2nYu1oGDuHqUcvDbstElGAJrn7u4QtP2Kgzd1GSkvbSKhsjR2RniiJ7cD278i27NAEPXY+qqmWQ4c+zt3BKG4Aj4EtKa/4AyARmLC78KjZpfiGPTUzQZbMQudAMmKgSTQhx7ONg==';

      // Policy used to generate signature.
      var policy = cryptoPolicy.newInstance();
      policy.asymmetric.signer = {
        algorithm: 'RSA',
        hashAlgorithm: 'SHA256',
        publicExponent: 65537,
      };

      var service = asymmetric.newService({policy: policy});
      var sigVerifier = service.newSignatureVerifier().init(PUBLIC_KEY_PEM);

      // Verify that digital signature was successfully verified.
      expect(sigVerifier.verify(
                 codec.base64Decode(signatureB64),
                 codec.utf8Encode(DATA_FROM_JAVA)))
          .toBeTruthy();
    });

    it('verify a signature that was generated using Java and RSA-PSS padding',
       function() {
         // Signature generated in Java.
         var signatureB64 =
             'JSYZ0i3Yz3L8J3bUOLOP/Kk83qkhoZ9NqBm9eUpaFoZY8gD42XHJxXyPmDYMnDFMr+J5GypfS9vheYtgn2hag8n3DcG86I80UCNuEZLEhyXpIsN4mv3rDb/xjMXlnDLWiK6MTBTDVImKfwpX6x/xw9YtcG9ADACRefH4++H9fhpg8yXUfT9OacOPHgjoW/y4hJmaKVk+IVDgLAKfToNWwVm2xU0SnFryQ9PUJeR8KHttBLR+gpZZpn+bQMcEvikw8bzAYGX4yXxGB9UgoIsz6xNyxY6P6UyJSal/JajURLuSwW7JpxjtthbyKS6SUXtH+NEg36ZpMhd8QC6EPzwrlQ==';

         // Policy used to generate signature.
         var policy = cryptoPolicy.newInstance();
         policy.asymmetric.signer = {
           algorithm: 'RSA',
           hashAlgorithm: 'SHA256',
           padding: {
             name: 'PSS',
             hashAlgorithm: 'SHA256',
             maskGenerator: {name: 'MGF1', hashAlgorithm: 'SHA256'},
             saltLengthBytes: 32
           },
           publicExponent: 65537,
         };

         var service = asymmetric.newService({policy: policy});
         var sigVerifier = service.newSignatureVerifier().init(PUBLIC_KEY_PEM);

         // Verify that digital signature was successfully verified.
         expect(sigVerifier.verify(
                    codec.base64Decode(signatureB64),
                    codec.utf8Encode(DATA_FROM_JAVA)))
             .toBeTruthy();
       });

    it('throw an error when being created, using the wrong signing algorithm',
       function() {
         policy_.asymmetric.signer.algorithm =
             'Wrong digital signature algorithm';
         var service = asymmetric.newService({policy: policy_});

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

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

    it('throw an error when being created, using the wrong hash algorithm',
       function() {
         policy_.asymmetric.signer.hashAlgorithm =
             'Wrong signer hash algorithm';
         var service = asymmetric.newService({policy: policy_});

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

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

    it('throw an error when being created, using the wrong padding name',
       function() {
         policy_.asymmetric.signer.padding.name = 'Wrong signer padding name';
         var service = asymmetric.newService({policy: policy_});

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

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

    it('throw an error when being created, using the wrong padding hash algorithm',
       function() {
         policy_.asymmetric.signer.padding.hashAlgorithm =
             'Wrong signer padding hash algorithm';
         var service = asymmetric.newService({policy: policy_});

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

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

    it('throw an error when being created, using the wrong padding mask generation function',
       function() {
         policy_.asymmetric.signer.padding.maskGenerator.name =
             'Wrong signer padding mask generation function';
         var service = asymmetric.newService({policy: policy_});

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

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

    it('throw an error when being created, using the wrong padding mask generation function hash algorithm',
       function() {
         policy_.asymmetric.signer.padding.maskGenerator.hashAlgorithm =
             'Wrong signer padding mask generation function hash algorithm';
         var service = asymmetric.newService({policy: policy_});

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

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

    it('throw an error when signing data, using a private key with the wrong public exponent',
       function() {
         expect(function() {
           signer_.sign(invalidKeyPair_.getPrivateKey().getPem(), data_);
         }).toThrow();
       });

    it('throw an error when verifying a signature, using a public key with the wrong public exponent',
       function() {
         expect(function() {
           sigVerifier_.verify(
               signature_, invalidKeyPair_.getPublicKey().getPem(), data_);
         }).toThrow();
       });
  });
});
