/*
 * 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
 */
describe('Signers: ', function() {
  'use strict';
  describe(' from the Forge provider ..', function() {
    describe('should be able to ..', function() {
      var _plaintext = 'Ox2fUJq1gAbX';
      var _privateKeyPem =
          '-----BEGIN RSA PRIVATE KEY-----MIIEowIBAAKCAQEAglypZU45bnf2opnRI+Y51VqouBpvDT33xIB/OtbwKzwVpi+JrjBFtfk33tE9t/dSRs79CK94HRhCWcOiLa2qWPrjeZ9SBiEyScrhIvRZVBF41zBgwQNuRvJCsKmAqlZaFNJDZxEP4repmlBn1CfVFmfrXmOKqwP5F7l9ZtucveRzsfmF1yVPFkW8TMuB3YqMiyymyqHlS8ujCsu5I8tpgPbwuxdMOY94fNhSXrYkY8IuX1g1zdq/Z1jluOaR/UqK4UpnbuJaH/F0VgDNiWh6cTD0DFGEk0b70i5wU4Q3L/S6XZQRvSuADoCbhwBKuFL5pW5n865oLVb5S3wuVdWaGwIDAQABAoIBAC/tn34Wf3kE9BGeGc1oFLVDaqqdVVz5/oEpeR2J7q0GnzMFYUpAhzC7WvY52cYsUPyll1Q9Jx0TUTmteo/uvKWQQFfz4nVMeS+2PoXabolBDzuWlsv/1eiRo0FOYHa/3siu8YcQN9X0DpAkpbfTmT1uoZOHZ3EuucMmOFu7vGn38Grw8bSxpR0uvTtnb8ygC+aB51y38RMyhzQQanrM8FMeAfDAy6IB0Yo7b0c50Cxa6Ax4nqn9LXyGakr5WeAMkgTIOA/GId9SZD4e5eRpq+628pOeR4O9datFltgl6r1+A4ii2VrJsDqeatGtODlX6KRKqwFHoGIa2TjgSZLuorECgYEAxeSZDOOgFsI5mB7RkRzZaQ9znJ15sgdyZiAFZAOUah4hSGdAXNAnZTlrdacduXEu3EfkpuPToX7xZSv5FRYwfBwMwCLeytlGLPjQzWejZGbo4+KqgzWb9fECDYVtDPlJ/+yLih9nt67BHweJKxYydl18rVigdVyy22X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0VgDNiWh6cTD0DFGEk0b70i5wU4Q3L/S6XZQRvSuADoCbhwBKuFL5pW5n865oLVb5S3wuVdWaGwIDAQAB-----END PUBLIC KEY-----';

      it('generate a signature for some data and verify the signature when SHA256withRSA is used',
         function() {
           cryptolib('asymmetric.signer', 'commons.utils', function() {

             var f = function(box) {

               var signerFactory =
                   new box.asymmetric.signer.factory.SignerFactory();
               var converters = new box.commons.utils.Converters();

               var cryptoForgeSigner = signerFactory.getCryptoSigner();

               var dataB64 = converters.base64Encode(_plaintext);

               var arrayDataBase64 = [dataB64];

               var signatureBase64 =
                   cryptoForgeSigner.sign(_privateKeyPem, arrayDataBase64);

               // Check whether digital signature can be verified.
               var verified = cryptoForgeSigner.verify(
                   signatureBase64, _publicKeyPem, arrayDataBase64);

               // Verify that digital signature was successfully verified.
               expect(verified).toBeTruthy();
             };

             f.policies = {
               asymmetric: {
                 signer: {
                   algorithm: 'RSA',
                   provider: 'Forge',
                   hash: 'SHA256',
                   publicExponent: 65537,
                   secureRandom: {provider: 'Scytl'}
                 }
               }
             };

             cryptolib('asymmetric.signer', 'commons.utils', f);
           });
         });

      it('generate a signature for some data and verify the signature when SHA256withRSA/PSS is used',
         function() {
           cryptolib('asymmetric.signer', 'commons.utils', function() {
             var f = function(box) {

               var signerFactory =
                   new box.asymmetric.signer.factory.SignerFactory();
               var converters = new box.commons.utils.Converters();

               var cryptoForgeSigner = signerFactory.getCryptoSigner();

               var dataB64 = converters.base64Encode(_plaintext);

               var arrayDataBase64 = [dataB64];
               var signatureBase64 =
                   cryptoForgeSigner.sign(_privateKeyPem, arrayDataBase64);

               // Check whether digital signature can be verified.
               var verified = cryptoForgeSigner.verify(
                   signatureBase64, _publicKeyPem, arrayDataBase64);

               // Verify that digital signature was successfully verified.
               expect(verified).toBeTruthy();
             };

             f.policies = {
               asymmetric: {
                 signer: {
                   algorithm: 'RSA',
                   provider: 'Forge',
                   hash: 'SHA256',
                   padding: {
                     PSS: {
                       name: 'PSS',
                       hash: 'SHA256',
                       mask: {MGF1: {name: 'MGF1', hash: 'SHA256'}},
                       saltLengthBytes: 32
                     }
                   },
                   publicExponent: 65537,
                   secureRandom: {provider: 'Scytl'}
                 }
               }
             };

             cryptolib('asymmetric.signer', 'commons.utils', f);
           });
         });

      it('generate a signature for an empty data and verify the signature when SHA256withRSA is used',
         function() {
           cryptolib('asymmetric.signer', 'commons.utils', function() {
             var f = function(box) {
               var signerFactory =
                   new box.asymmetric.signer.factory.SignerFactory();
               var converters = new box.commons.utils.Converters();

               var cryptoForgeSigner = signerFactory.getCryptoSigner();

               var dataB64 = converters.base64Encode('');

               var arrayDataBase64 = [dataB64];

               var signatureBase64 =
                   cryptoForgeSigner.sign(_privateKeyPem, arrayDataBase64);

               // Check whether digital signature can be verified.
               var verified = cryptoForgeSigner.verify(
                   signatureBase64, _publicKeyPem, arrayDataBase64);

               // Verify that digital signature was successfully verified.
               expect(verified).toBeTruthy();
             };

             f.policies = {
               asymmetric: {
                 signer: {
                   algorithm: 'RSA',
                   provider: 'Forge',
                   hash: 'SHA256',
                   publicExponent: 65537,
                   secureRandom: {provider: 'Scytl'}
                 }
               }
             };

             cryptolib('asymmetric.signer', 'commons.utils', f);
           });
         });

      it('detect a null element in data when signing', function() {
        cryptolib('asymmetric.signer', 'commons.utils', function() {
          var f = function(box) {
            var signerFactory =
                new box.asymmetric.signer.factory.SignerFactory();
            var converters = new box.commons.utils.Converters();

            var cryptoForgeSigner = signerFactory.getCryptoSigner();

            var dataElement1 = 'dataElement1';
            var dataElement2 = 'dataElement2';
            var dataElement3 = null;
            var dataElement4 = 'dataElement4';

            var dataElement1B64 = converters.base64Encode(dataElement1);
            var dataElement2B64 = converters.base64Encode(dataElement2);
            var dataElement4B64 = converters.base64Encode(dataElement4);

            var arrayDataBase64 = [
              dataElement1B64, dataElement2B64, dataElement3, dataElement4B64
            ];

            var call = function() {
              cryptoForgeSigner.sign(_privateKeyPem, arrayDataBase64);
            };
            expect(call).toThrow();
          };

          f.policies = {
            asymmetric: {
              signer: {
                algorithm: 'RSA',
                provider: 'Forge',
                hash: 'SHA256',
                publicExponent: 65537,
                secureRandom: {provider: 'Scytl'}
              }
            }
          };

          cryptolib('asymmetric.signer', 'commons.utils', f);
        });
      });

      it('detect that a signature is false when SHA256withRSA is used',
         function() {
           cryptolib('asymmetric.signer', 'commons.utils', function() {
             var f = function(box) {

               var signerFactory =
                   new box.asymmetric.signer.factory.SignerFactory();
               var converters = new box.commons.utils.Converters();

               var cryptoForgeSigner = signerFactory.getCryptoSigner();

               var dataB64 = converters.base64Encode(_plaintext);
               var dataB64Different =
                   converters.base64Encode('Some other string.');

               var arrayDataBase64 = [dataB64];
               var arrayDataBase64Different = [dataB64Different];

               var signatureBase64 =
                   cryptoForgeSigner.sign(_privateKeyPem, arrayDataBase64);

               // Check whether digital signature can be verified.
               var verified = cryptoForgeSigner.verify(
                   signatureBase64, _publicKeyPem, arrayDataBase64Different);

               // Verify that digital signature was successfully verified.
               expect(!verified).toBeTruthy();
             };


             f.policies = {
               asymmetric: {
                 signer: {
                   algorithm: 'RSA',
                   provider: 'Forge',
                   hash: 'SHA256',
                   publicExponent: 65537,
                   secureRandom: {provider: 'Scytl'}
                 }
               }
             };

             cryptolib('asymmetric.signer', 'commons.utils', f);
           });
         });

      it('detect that a signature is false when SHA256withRSA/PSS is used',
         function() {
           cryptolib('asymmetric.signer', 'commons.utils', function() {
             var f = function(box) {

               var signerFactory =
                   new box.asymmetric.signer.factory.SignerFactory();
               var converters = new box.commons.utils.Converters();

               var cryptoForgeSigner = signerFactory.getCryptoSigner();

               var dataB64 = converters.base64Encode(_plaintext);
               var dataB64Different =
                   converters.base64Encode('Some other string.');

               var arrayDataBase64 = [dataB64];
               var arrayDataBase64Different = [dataB64Different];

               var signatureBase64 =
                   cryptoForgeSigner.sign(_privateKeyPem, arrayDataBase64);

               // Check whether digital signature can be verified.
               var verified = cryptoForgeSigner.verify(
                   signatureBase64, _publicKeyPem, arrayDataBase64Different);

               // Verify that digital signature was successfully verified.
               expect(!verified).toBeTruthy();
             };


             f.policies = {
               asymmetric: {
                 signer: {
                   algorithm: 'RSA',
                   provider: 'Forge',
                   hash: 'SHA256',
                   padding: {
                     PSS: {
                       name: 'PSS',
                       hash: 'SHA256',
                       mask: {MGF1: {name: 'MGF1', hash: 'SHA256'}},
                       saltLengthBytes: 32
                     }
                   },
                   publicExponent: 65537,
                   secureRandom: {provider: 'Scytl'}
                 }
               }
             };

             cryptolib('asymmetric.signer', 'commons.utils', f);
           });
         });

      it('verify a RSA signature that was generated in Java', function() {
        cryptolib('asymmetric.signer', 'commons.utils', function() {
          var f = function(box) {

            var signerFactory =
                new box.asymmetric.signer.factory.SignerFactory();
            var converters = new box.commons.utils.Converters();

            var cryptoForgeSigner = signerFactory.getCryptoSigner();

            var signedData = 'This is a string from Java.';
            var signedDataB64 = converters.base64Encode(signedData);
            var arraySignedDataB64 = [signedDataB64];

            // this is a signature generated in Java (using RSA)
            var signatureFromJavaRsa =
                'KuQPmBRE/JpNQ5mvh1Y1LvW3Jr/ZYlYqOgdbgXLVZp+gjVtXHDgFZzIrC8+S+VdTs9WINjxN8aIZlbiemZ+YvXZ7fDOoJsZJRboyrFN9VGz6sWWVXAv28Xj1a2lPNlys8dO3uY0s5R77kDCvBHV4nJh0Hq2Ry+JRjRcrlPsIiDWzm9iTY7V6XzkVGCo58qWyQtloC0s73i8UM6V2nYu1oGDuHqUcvDbstElGAJrn7u4QtP2Kgzd1GSkvbSKhsjR2RniiJ7cD278i27NAEPXY+qqmWQ4c+zt3BKG4Aj4EtKa/4AyARmLC78KjZpfiGPTUzQZbMQudAMmKgSTQhx7ONg==';

            // Check whether digital signature can be verified.
            var verified = cryptoForgeSigner.verify(
                signatureFromJavaRsa, _publicKeyPem, arraySignedDataB64);

            // Verify that digital signature was successfully verified.
            expect(verified).toBeTruthy();
          };

          f.policies = {
            asymmetric: {
              signer: {
                algorithm: 'RSA',
                provider: 'Forge',
                hash: 'SHA256',
                publicExponent: 65537,
                secureRandom: {provider: 'Scytl'}
              }
            }
          };

          cryptolib('asymmetric.signer', 'commons.utils', f);
        });
      });


      it('verify a RSA/PSS signature that was generated in Java', function() {
        cryptolib('asymmetric.signer', 'commons.utils', function() {
          var f = function(box) {
            var signerFactory =
                new box.asymmetric.signer.factory.SignerFactory();
            var converters = new box.commons.utils.Converters();

            var cryptoForgeSigner = signerFactory.getCryptoSigner();

            var signedData = 'This is a string from Java.';
            var signedDataB64 = converters.base64Encode(signedData);
            var arraySignedDataB64 = [signedDataB64];

            // This is a signature generated in Java (using RSA/PSS)
            var signatureFromJavaRsa =
                'JSYZ0i3Yz3L8J3bUOLOP/Kk83qkhoZ9NqBm9eUpaFoZY8gD42XHJxXyPmDYMnDFMr+J5GypfS9vheYtgn2hag8n3DcG86I80UCNuEZLEhyXpIsN4mv3rDb/xjMXlnDLWiK6MTBTDVImKfwpX6x/xw9YtcG9ADACRefH4++H9fhpg8yXUfT9OacOPHgjoW/y4hJmaKVk+IVDgLAKfToNWwVm2xU0SnFryQ9PUJeR8KHttBLR+gpZZpn+bQMcEvikw8bzAYGX4yXxGB9UgoIsz6xNyxY6P6UyJSal/JajURLuSwW7JpxjtthbyKS6SUXtH+NEg36ZpMhd8QC6EPzwrlQ==';

            // Check whether digital signature can be verified.
            var verified = cryptoForgeSigner.verify(
                signatureFromJavaRsa, _publicKeyPem, arraySignedDataB64);

            // Verify that digital signature was successfully verified.
            expect(verified).toBeTruthy();
          };

          f.policies = {
            asymmetric: {
              signer: {
                algorithm: 'RSA',
                provider: 'Forge',
                hash: 'SHA256',
                padding: {
                  PSS: {
                    name: 'PSS',
                    hash: 'SHA256',
                    mask: {MGF1: {name: 'MGF1', hash: 'SHA256'}},
                    saltLengthBytes: 32
                  }
                },
                publicExponent: 65537,
                secureRandom: {provider: 'Scytl'}
              }
            }
          };

          cryptolib('asymmetric.signer', 'commons.utils', f);
        });
      });

      it('generate a RSA digital signature for some data and verify the signature.',
         function() {
           cryptolib('asymmetric.signer', 'commons.utils', function(box) {
             var signerFactory =
                 new box.asymmetric.signer.factory.SignerFactory();
             var converters = new box.commons.utils.Converters();

             var cryptoForgeSigner = signerFactory.getCryptoSigner();

             var dataB64 = converters.base64Encode(_plaintext);

             var arrayDataBase64 = [dataB64];

             var signatureBase64 =
                 cryptoForgeSigner.sign(_privateKeyPem, arrayDataBase64);

             // Check whether digital signature can be verified.
             var verified = cryptoForgeSigner.verify(
                 signatureBase64, _publicKeyPem, arrayDataBase64);

             // Verify that digital signature was successfully verified.
             expect(verified).toBeTruthy();
           });
         });

      it('throw an error when the array of data is null.', function() {
        cryptolib('asymmetric.signer', function(box) {
          var signerFactory = new box.asymmetric.signer.factory.SignerFactory();

          var cryptoForgeSigner = signerFactory.getCryptoSigner();

          expect(function() {
            cryptoForgeSigner.sign(_privateKeyPem, null);
          }).toThrow();
        });
      });

      it('throw an error when the array of data contains less than one element.',
         function() {
           cryptolib('asymmetric.signer', function(box) {
             var signerFactory =
                 new box.asymmetric.signer.factory.SignerFactory();

             var cryptoForgeSigner = signerFactory.getCryptoSigner();

             var arrayDataBase64 = [];

             expect(function() {
               cryptoForgeSigner.sign(_privateKeyPem, arrayDataBase64);
             }).toThrow();
           });
         });

      it('throw an error when the given algorithm is wrong.', function() {

        var f = function(box) {
          var signerFactory = new box.asymmetric.signer.factory.SignerFactory();
          expect(function() {
            signerFactory.getCryptoSigner();
          }).toThrow();
        };
        f.policies = {
          asymmetric: {
            signer: {
              algorithm: 'WRONG',
              provider: 'Forge',
              secureRandom: {provider: 'Scytl'}
            }
          }
        };
        cryptolib('asymmetric.signer', f);
      });

      it('throw an error when the given provider is wrong.', function() {
        var f = function(box) {
          var signerFactory = new box.asymmetric.signer.factory.SignerFactory();
          expect(function() {
            signerFactory.getCryptoSigner();
          }).toThrow();
        };
        f.policies = {
          asymmetric: {
            signer: {
              algorithm: 'CORRECT',
              provider: 'WRONG',
              secureRandom: {provider: 'Scytl'}
            }
          }
        };
        cryptolib('asymmetric.signer', f);
      });

      it('throw an error when the given hash algorithm is wrong.', function() {
        var f = function(box) {
          var signerFactory = new box.asymmetric.signer.factory.SignerFactory();
          expect(function() {
            signerFactory.getCryptoSigner();
          }).toThrow();
        };
        f.policies = {
          asymmetric: {
            signer: {
              algorithm: 'RSA',
              hash: 'WRONG',
              provider: 'Forge',
              secureRandom: {provider: 'Scytl'}
            }
          }
        };
        cryptolib('asymmetric.signer', f);
      });
    });
  });
});
