/*
 * 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('Stores', function() {
  'use strict';

  var _testString = 'Ox2fUJq1gAbX';
  var _testPassword = 'PM6XtkOTbefJmhHGFgbz';
  var _rootRsaPrivateKeyAlias = 'root_rsa_private_key';
  var _userRsaPrivateKeyAlias = 'user_rsa_private_key';
  var _pkcs12DerBase64 =
      '[encoded data, 8884 characters]';
  var _rootCn = 'Root CN';
  var _userCn = 'Subject CN';
  var _rootRsaPrivateKeyPem =
      '-----BEGIN RSA PRIVATE KEY-----MIIEogIBAAKCAQEAngCJ2RYh3XOvghmAi2MT26/fx4Hx8gYkYS2zaf9c2H8Qns1hnIHO8pIlHze/stUmNzim6nlytbJLQHmVDu64Pf9dn1ClAW2caKqUo4ofjnOzDd6RocQByjTsvZ1nOcG5BMYtOWGua+QIVFrxvxZgL6T3ShQ+9J3/1LiQDUmWj0kMoct6vRJuNkJxVFegtIEqYZYTTFI1+Y25k040NFu0e9IDwDXQA63EqKL3DjrgxdjOY+KXu4zU6DUcL4VcKaTMs1+pDfU6bSOtrecuasKkEmNE9fuy9WejFqNGqlrNVCeYmOOnNXvI0vCdH1bw4/CpqddxvGZOStczF8vGJVcMVQIDAQABAoIBAB/MEfHLP3N2pZp0EWd7v/JVOZ7H6u3/CHE6JkItrvyuzaR3xq4dfY1ZlfjrWjveI3u3fffwCwK/598I2NORfSiU7L10GFDqQzDZK2KiGGmtpRokcYBxlr6f2gjq1WxNLTPlwhIrM1PpJzf6uW3wTdkoxM92tZi691JS9kKGTbN1+LWIITWk6sC3n4Atu8LI19/zSfrl16/1iYSF7n9ylz2tyqQAyBEQXgrMRrg3KkPU83P5CwdIdDFyb4pwZ75U8OXuOfhcv0ilGIH62t2d9eVaFw0RKSf4QOYAdcVPAA75m+RzTSM7jDX4OGiPsoa1iWS4fqcdPfchFQSnJhhrL2ECgYEA8VV9JMYKE4qRY/srxhKnsV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i8vY3JsLnZlcmlzaWduLmNvbS9wY2EzLmNybDArBgNVHREBAf8EITAfpB0wGzEZMBcGA1UEAwwQUHJpdmF0ZUxhYmVsMy0xNTAOBgNVHQ8BAf8EBAMCAQYwNwYDVR0lAQH/BC0wKwYIKwYBBQUHAwEGCCsGAQUFBwMCBgpghkgBhvhFAQgBBglghkgBhvhCBAEwDQYJKoZIhvcNAQELBQADggEBADmtmjApZAXIkGLaZCdkRnhel53BtEdQnG990Oo/tBBboqy2ipum9ByTj3hNWJB3zuPN77rkrek9rbookNcCgVWhHtTk1lUpUK6ZohDsZh8k0MqIhkz+X+HiWGRsEOptjsCaknyWcWb4aXAevMAQMPm/ktkpQ8AOxAq+gtieewWQZP3kGPhBBCfn8TGjdrn9+ymf8EIbAUFXQ8m+oWeNlrdWhqzRXwQbj4EDds1kZdTo0nCYUdH+XEBF9nMyhAxSQWzCKQQTRFWv1dr3dKapzfgrdH8wEgvptiBYCY62O5+3DxiNK/VWquHz6S5GqIwkmSPDPMUU/qK3SNG3xIL1U1k=-----END CERTIFICATE-----';
  var _userX509CertificatePem =
      '-----BEGIN CERTIFICATE-----MIIEMzCCAxugAwIBAgIQRbaPaToIM+VS/d6etgYZ4jANBgkqhkiG9w0BAQsFADBUMRAwDgYDVQQDDAdSb290IENOMRYwFAYDVQQLDA1Sb290IE9yZyBVbml0MREwDwYDVQQKDAhSb290IE9yZzEVMBMGA1UEBhMMUm9vdCBDb3VudHJ5MB4XDTE0MDYxODEwMjMyOFoXDTE1MDYxODEwMjMyOFowYDETMBEGA1UEAwwKU3ViamVjdCBDTjEZMBcGA1UECwwQU3ViamVjdCBPcmcgVW5pdDEUMBIGA1UECgwLU3ViamVjdCBPcmcxGDAWBgNVBAYTD1N1YmplY3QgQ291bnRyeTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAIJcqWVOOW539qKZ0SPmOdVaqLgabw0998SAfzrW8Cs8FaYvia4wRbX5N97RPbf3UkbO/QiveB0YQlnDoi2tqlj643mfUgYhMknK4SL0WVQReNcwYMEDbkbyQrCpgKpWWhTSQ2cRD+K3qZpQZ9Qn1RZn615jiqsD+Re5fWbbnL3kc7H5hdclTxZFvEzLgd2KjIsspsqh5UvLowrLuSPLaYD28LsXTDmPeHzYUl62JGPCLl9YNc3av2dY5bjmkf1KiuFKZ27iWh/xdFYAzYloenEw9AxRhJNG+9IucFOENy/0ul2UEb0rgA6Am4cASrhS+aVuZ/OuaC1W+Ut8LlXVmhsCAwEAAaOB9DCB8TAMBgNVHRMBAf8EAjAAMDUGCCsGAQUFBwEBAQH/BCYwJDAiBggrBgEFBQcwAYYWaHR0cDovL29jc3AudGhhd3RlLmNvbTA0BgNVHR8BAf8EKjAoMCagJKAihiBodHRwOi8vY3JsLnZlcmlzaWduLmNvbS9wY2EzLmNybDArBgNVHREBAf8EITAfpB0wGzEZMBcGA1UEAwwQUHJpdmF0ZUxhYmVsMy0xNTAOBgNVHQ8BAf8EBAMCBsAwNwYDVR0lAQH/BC0wKwYIKwYBBQUHAwEGCCsGAQUFBwMCBgpghkgBhvhFAQgBBglghkgBhvhCBAEwDQYJKoZIhvcNAQELBQADggEBAAWZDJD6bg4ohHewszrAbL2tdUNxhrwCgNaHUhwNK43kiLGH0U9innhL1i0jP1VHNkL1G/+ZCo1qzh/Usji/jtlurfAWtrXku6VRF9NP+itKOY5jJ91Ijkc7t4dgoeJq6iMHn6JbDKIQ88r/Ikd0GdF04o5Qjqq1HlUVmqyIOHeHFla4i4tOxTyUBj34eE1No/xmaKYV1QtR1dqSHblR7OagEo7Dd3fXp7iSrKrXaN0Ef/6zeF3zjU5SMKcUcU9d3CbhS/CrGb+UGlqTXgzPXQWESH9AqBNl67+HF3mYktDQOZYPT5WRO5IKSko2cy9pP9UCsLk4oU3xyOxacWDpk1k=-----END CERTIFICATE-----';

  // Test opening PKCS12 and retrieving multiple private keys.
  describe('Pkcs12 ...', function() {
    describe('should be able to ..', function() {
      it('retrieve its private key chain and certificate chain, when PKCS12 was generated using Java.',
         function() {
           cryptolib(
               'stores.pkcs12', 'certificates', 'asymmetric.signer',
               'primitives.securerandom', 'commons.utils', function(box) {
                 // Retrieve PKCS12.
                 var pkcs12 = new box.stores.pkcs12.Pkcs12(_pkcs12DerBase64);
                 var converters = new box.commons.utils.Converters();

                 // Retrieve private key chain from PKCS12.
                 var passwordBase64Encoded =
                     converters.base64Encode(_testPassword);
                 var privateKeyChain =
                     pkcs12.getPrivateKeyChain(passwordBase64Encoded);
                 var userPrivateKeyPem =
                     privateKeyChain.get(_userRsaPrivateKeyAlias)
                         .replace(/(\r\n|\n|\r)/gm, '');
                 var userPrivateKey =
                     forge.pki.privateKeyFromPem(_userRsaPrivateKeyPem);
                 var rootPrivateKeyPem =
                     privateKeyChain.get(_rootRsaPrivateKeyAlias)
                         .replace(/(\r\n|\n|\r)/gm, '');
                 var rootPrivateKey =
                     forge.pki.privateKeyFromPem(rootPrivateKeyPem);

                 // Retrieve certificate chain from PKCS12, in PEM format.
                 var userCertificatePem =
                     pkcs12
                         .getCertificateBySubject(
                             passwordBase64Encoded, _userCn)
                         .replace(/(\r\n|\n|\r)/gm, '');
                 var rootCertificatePem =
                     pkcs12
                         .getCertificateBySubject(
                             passwordBase64Encoded, _rootCn)
                         .replace(/(\r\n|\n|\r)/gm, '');

                 // Retrieve user public key from PKCS12.
                 var userPublicKey =
                     forge.pki.certificateFromPem(userCertificatePem).publicKey;
                 var userPublicKeyPem = forge.pki.publicKeyToPem(userPublicKey)
                                            .replace(/(\r\n|\n|\r)/gm, '');

                 // Check whether user key pair retrieved from PKCS12 is same as
                 // original.
                 var userPrivateKeyOrig =
                     forge.pki.privateKeyFromPem(_userRsaPrivateKeyPem);
                 expect(userPrivateKey.p).toEqual(userPrivateKeyOrig.p);
                 expect(userPrivateKey.q).toEqual(userPrivateKeyOrig.q);
                 var userPublicKeyOrig =
                     forge.pki.publicKeyFromPem(_userRsaPublicKeyPem);
                 expect(userPublicKey.e).toEqual(userPublicKeyOrig.e);
                 expect(userPublicKey.n).toEqual(userPublicKeyOrig.n);
                 expect(userPublicKeyPem).toBe(_userRsaPublicKeyPem);

                 var dataB64 = converters.base64Encode(_testString);
                 var arrayDataBase64 = [dataB64];

                 // Check whether retrieved user key pair can be used to
                 // generate and verify a signature.
                 var signerFactory =
                     new box.asymmetric.signer.factory.SignerFactory();
                 var rsaSigner = signerFactory.getCryptoSigner();
                 var signatureB64 =
                     rsaSigner.sign(userPrivateKeyPem, arrayDataBase64);
                 expect(rsaSigner.verify(
                            signatureB64, userPublicKeyPem, arrayDataBase64))
                     .toBeTruthy();

                 // Retrieve root public key from PKCS12, in PEM format.
                 var rootPublicKey =
                     forge.pki.certificateFromPem(rootCertificatePem).publicKey;
                 var rootPublicKeyPem = forge.pki.publicKeyToPem(rootPublicKey)
                                            .replace(/(\r\n|\n|\r)/gm, '');

                 // Check whether root key pair retrieved from PKCS12 is same as
                 // original.
                 var rootPrivateKeyOrig =
                     forge.pki.privateKeyFromPem(_rootRsaPrivateKeyPem);
                 expect(rootPrivateKey.p).toEqual(rootPrivateKeyOrig.p);
                 expect(rootPrivateKey.q).toEqual(rootPrivateKeyOrig.q);
                 var rootPublicKeyOrig =
                     forge.pki.publicKeyFromPem(_rootRsaPublicKeyPem);
                 expect(rootPublicKey.e).toEqual(rootPublicKeyOrig.e);
                 expect(rootPublicKey.n).toEqual(rootPublicKeyOrig.n);
                 expect(rootPublicKeyPem).toBe(_rootRsaPublicKeyPem);

                 // Check whether retrieved root key pair can be used to
                 // generate and verify a signature.
                 signatureB64 =
                     rsaSigner.sign(rootPrivateKeyPem, arrayDataBase64);
                 expect(rsaSigner.verify(
                            signatureB64, rootPublicKeyPem, arrayDataBase64))
                     .toBeTruthy();

                 // Check whether certificate chain retrieved from PKCS12 is
                 // same as original.
                 expect(userCertificatePem).toBe(_userX509CertificatePem);
                 expect(rootCertificatePem).toBe(_rootX509CertificatePem);

                 // Verify signatures of certificate chain retrieved from
                 // PKCS12.
                 var rootCertificate =
                     new box.certificates.CryptoX509Certificate(
                         rootCertificatePem);
                 expect(rootCertificate.verify(rootCertificatePem))
                     .toBeTruthy();
                 expect(rootCertificate.verify(userCertificatePem))
                     .toBeTruthy();
               });
         });
    });
  });
});
