public void should_be_able_to_encrypted_string()
        {
            var encryptedString = Crypto.Encrypt(ClearString);

            encryptedString.ShouldNotBeEmpty();
            encryptedString.ShouldNotBe(ClearString);
        }
        public void SameInputEncryptedTwiceComparison()
        {
            var service = new CryptographyService();
            var input   = "test";

            var encryptOne = service.Encrypt(input);
            var encryptTwo = service.Encrypt(input);

            Assert.AreEqual(encryptOne, encryptTwo);
        }
        public void EncryptClearText_CanBeReEncodedWithSameSalt()
        {
            const string clear = "TooManySecrets";
            const string salt  = "salt";

            var srv  = new CryptographyService();
            var encA = srv.Encrypt(clear, salt);
            var encB = srv.Encrypt(clear, salt);

            Assert.AreEqual(encA, encB);
        }
        public void EncryptClearTest_AutoGeneratedSalt_ReturnsEncodedStringContainingSalt()
        {
            const string clear = "TooManySecrets";
            var          srv   = new CryptographyService();
            var          enc   = srv.Encrypt(clear);

            Assert.IsTrue(enc.Contains("#-#"));
        }
Ejemplo n.º 5
0
        public void Encrypt_DataListNull_ThrowsArgumentNullException()
        {
            var factory = Substitute.For <ICryptographyProcessorFactory>();
            var svc     = new CryptographyService(factory);

            var e = Assert.Throws <ArgumentNullException>(() => svc.Encrypt((List <string>)null));

            Assert.That(e.Message, Does.Contain("data"));
        }
Ejemplo n.º 6
0
        public void RequiresObjectToEncrypt()
        {
            //Arrange
            string objectToEncrypt = null;
            var    cryptoService   = new CryptographyService <string>(provider);

            //Act && Assert
            Assert.Throws <ArgumentNullException>(() => cryptoService.Encrypt(objectToEncrypt));
        }
Ejemplo n.º 7
0
        public void Encrypt_Settings_test()
        {
            var cryptographyService = new CryptographyService(WinRTCrypto.CryptographicEngine, WinRTCrypto.SymmetricKeyAlgorithmProvider, WinRTCrypto.HashAlgorithmProvider, new Logger());

            var valueString         = "3nNkJ5EcI7yyi56ifLSAA";
            var encrypted           = cryptographyService.Encrypt(valueString);
            var encryptedWithoutPcl = SettingsEncryptorWithoutPcl.Encrypt(valueString);

            Assert.AreEqual(encrypted, encryptedWithoutPcl);
        }
Ejemplo n.º 8
0
        public void SendResetPasswordMail(long userId, string fullname, long createdByOrgRoleUserId, string source)
        {
            string resetPasswordQueryString = _cryptographyService.Encrypt(DateTime.Now.ToLongDateString()).Replace("+", "X");

            _userLoginRepository.UpdateResetPasswordQueryString(userId, resetPasswordQueryString);

            var resetPassword = _emailNotificationModelsFactory.GetResetNotificationModel(userId, fullname, resetPasswordQueryString);

            _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.ResetMail, EmailTemplateAlias.ResetPassword, resetPassword, userId, createdByOrgRoleUserId, source);
        }
        public void EncryptClearTest_ReturnsEncodedString()
        {
            const string clear   = "TooManySecrets";
            const string encText = "tekaZ6H2yJ/k1hnuKbwBJH3WNqxoUEZNIOIxzR0EV5E=";
            const string salt    = "salt";

            var srv = new CryptographyService();
            var enc = srv.Encrypt(clear, salt);

            Assert.AreEqual(encText, enc);
        }
Ejemplo n.º 10
0
        public void Encrypt_DataValid_EncryptionProcessorReceivedCall()
        {
            var factory             = Substitute.For <ICryptographyProcessorFactory>();
            var encryptionProcessor = Substitute.For <IEncryptionProcessor>();

            factory.GetEncryptionProcessor().Returns(encryptionProcessor);

            var svc = new CryptographyService(factory);

            svc.Encrypt("Test Data");

            encryptionProcessor.Received().Encrypt("Test Data");
        }
Ejemplo n.º 11
0
        public void RoundTrip()
        {
            //Arrange
            var original      = new Fixture().Create <NestedComplexObject>();
            var cryptoService = new CryptographyService <NestedComplexObject>(provider);

            //Act
            var encrypted = cryptoService.Encrypt(original);
            var roundtrip = cryptoService.Decrypt(encrypted);


            //Assert
            roundtrip.ShouldBeEquivalentTo(original);
        }
Ejemplo n.º 12
0
        public UserLoginEntity CreateUserLoginEntity(UserLogin userLogin, long userId)
        {
            if (userLogin == null)
            {
                throw new ArgumentNullException("userLogin");
            }
            string password = string.Empty;
            string salt     = string.Empty;

            if (userId == 0 && !string.IsNullOrEmpty(userLogin.Password) && string.IsNullOrEmpty(userLogin.Salt))
            {
                var secureHash = _oneWayHashingService.CreateHash(userLogin.Password);
                password = secureHash.HashedText;
                salt     = secureHash.Salt;
            }
            else
            {
                if (!string.IsNullOrEmpty(userLogin.Password) && string.IsNullOrEmpty(userLogin.Salt))
                {
                    var secureHash = _oneWayHashingService.CreateHash(userLogin.Password);
                    password = secureHash.HashedText;
                    salt     = secureHash.Salt;
                }
                else
                {
                    password = userLogin.Password;
                    salt     = userLogin.Salt;
                }
            }

            return(new UserLoginEntity(userLogin.Id == 0 ? userId : userLogin.Id)
            {
                UserName = userLogin.UserName,
                Password = password,
                Salt = salt,
                IsActive = true,
                DateCreated =
                    userLogin.DateCreated != DateTime.MinValue ? userLogin.DateCreated : DateTime.Now,
                DateModified = DateTime.Now,
                IsLocked = userLogin.Locked,
                LoginAttempts = userLogin.FailedAttempts,
                UserVerified = userLogin.UserVerified,
                HintAnswer = !string.IsNullOrEmpty(userLogin.HintAnswer) ? _cryptographyService.Encrypt(userLogin.HintAnswer) : userLogin.HintAnswer,
                HintQuestion = userLogin.HintQuestion,
                IsSecurityQuestionVerified = userLogin.IsSecurityQuestionVerified,
                IsNew = userLogin.Id == 0,
                LastPasswordChangeDate = userLogin.LastPasswordChangeDate != DateTime.MinValue ? userLogin.LastPasswordChangeDate : DateTime.Now,
                IsTwoFactorAuthrequired = userLogin.IsTwoFactorAuthrequired
            });
        }
        public void EncryptTextContainingSalt_AllowsReEncoding_ReturnsTrueMatching()
        {
            const string clear = "TooManySecrets";
            var          srv   = new CryptographyService();
            var          enc   = srv.Encrypt(clear);

            var splitIdx = enc.IndexOf("#-#", StringComparison.InvariantCulture);
            var salt     = enc.Substring(0, splitIdx);
            var encText  = enc.Substring(splitIdx + 3);

            srv = new CryptographyService();
            var newEnc = srv.Encrypt(clear, salt);

            Assert.AreEqual(enc, salt + "#-#" + newEnc);
        }
        private async Task ProcessSend(byte[] buffer, int offset, int size, int alignmentSize)
        {
            await _processSend.WaitAsync();

            try
            {
                _sendStopwatch.Restart();
                unsafe
                {
                    fixed(byte *ptr = buffer)
                    {
                        var header = (NetworkMessageHeader *)ptr;

                        header->Serial      = MessageSerialService.ComputeSend(buffer, offset);
                        header->Checksum    = _messageChecksumService.Compute(buffer, offset);
                        header->BodyLength += (ushort)alignmentSize;
                    }
                }
#if DEBUG
                LogPacket(buffer, offset, size, "Send");
#endif
                CryptographyService.Encrypt(buffer, offset, size + alignmentSize);
                if (_alignBuffer)
                {
                    buffer[offset + alignmentSize + size] = (byte)(alignmentSize ^ buffer[3]);
                }
                await _connection.WriteAsync(buffer, offset, size + alignmentSize + (_alignBuffer ? 1 : 0));
            }
            catch (SocketException ex)
            {
                await DisconnectAsync();

                Logger.LogTrace(ex.Message, "ProcessSend");
            }
            catch (IOException ex)
            {
                await DisconnectAsync();

                Logger.LogTrace(ex.Message, "ProcessSend");
            }
            finally
            {
                ArrayPool <byte> .Shared.Return(buffer);

                _sendStopwatch.Stop();
                _processSend.Release();
            }
        }
        public void Configure(EntityTypeBuilder <User> builder)
        {
            builder.ToContainer("Users");
            builder.HasNoDiscriminator();

            var converter = new ValueConverter <string, string>(
                value => CryptographyService.Encrypt(value, _appSettings.EncryptionKey),
                value => CryptographyService.Decrypt(value, _appSettings.EncryptionKey));

            builder.Property(user => user.Name).HasConversion(converter);
            builder.Property(user => user.Surname).HasConversion(converter);
            builder.Property(user => user.CellphoneNumber).HasConversion(converter);
            builder.Property(user => user.EmailAddress).HasConversion(converter);
            builder.Property(user => user.Password).HasConversion(converter);
            builder.Property(user => user.PasswordSalt).HasConversion(converter);
        }
Ejemplo n.º 16
0
        private void SendNotificationMail(UserEditModel userEditModel)
        {
            var notifier = IoC.Resolve <INotifier>();
            var emailNotificationModelsFactory = IoC.Resolve <IEmailNotificationModelsFactory>();
            var currentSession = IoC.Resolve <ISessionContext>().UserSession;

            var welcomeEmailViewModel = emailNotificationModelsFactory.GetWelcomeWithUserNameNotificationModel(userEditModel.UserName, userEditModel.FullName.FullName, userEditModel.DataRecorderMetaData.DateCreated);

            notifier.NotifySubscribersViaEmail(NotificationTypeAlias.EmployeeWelcomeEmailWithUsername, EmailTemplateAlias.EmployeeWelcomeEmailWithUsername, welcomeEmailViewModel, userEditModel.Id, currentSession.CurrentOrganizationRole.OrganizationRoleUserId, Request.Url.AbsolutePath);

            string resetPasswordQueryString = _cryptographyService.Encrypt(DateTime.Now.ToLongDateString()).Replace("+", "X");
            var    welcomePasswordViewModel = emailNotificationModelsFactory.GetWelcomeWithPasswordNotificationModel(userEditModel.FullName.FullName, userEditModel.Password, resetPasswordQueryString, userEditModel.Id);

            notifier.NotifySubscribersViaEmail(NotificationTypeAlias.EmployeeWelcomeEmailWithResetMail, EmailTemplateAlias.EmployeeWelcomeEmailWithPassword, welcomePasswordViewModel, userEditModel.Id, currentSession.CurrentOrganizationRole.OrganizationRoleUserId, Request.Url.AbsolutePath);

            var userLoginRepository = IoC.Resolve <IUserLoginRepository>();

            userLoginRepository.UpdateResetPasswordQueryString(userEditModel.Id, resetPasswordQueryString);
        }
Ejemplo n.º 17
0
        public void Encrypt_DataListContainsThreeValidItems_EncryptionProcessorReceivedThreeCalls()
        {
            var factory             = Substitute.For <ICryptographyProcessorFactory>();
            var encryptionProcessor = Substitute.For <IEncryptionProcessor>();

            factory.GetEncryptionProcessor().Returns(encryptionProcessor);

            var svc = new CryptographyService(factory);

            var strings = new List <string>()
            {
                "one",
                "two",
                "three"
            };

            svc.Encrypt(strings);

            encryptionProcessor.Received(3).Encrypt(Arg.Any <string>());
        }
Ejemplo n.º 18
0
    //public void LoadEventSummaryPanel(EEvent eventData)
    public void LoadEventSummaryPanel(EventMetricsViewData eventMetricsViewData, EventHostViewData eventHostViewData, EEvent eventPodDetails)
    {
        if (eventMetricsViewData == null || eventHostViewData == null)
        {
            return;
        }

        // format phone no.
        var commonCode = new CommonCode();

        string key = EPDFType.ResultPdf + "~" + eventHostViewData.EventId + "~0~" + "ALL";

        key = _cryptographyService.Encrypt(key);
        aPrintBulkResult.HRef = "javascript:showClinicalForm('" + key + "');";

        key = EPDFType.ClinicalForm + "~" + eventHostViewData.EventId + "~0~" + "ALL";
        key = _cryptographyService.Encrypt(key);
        aPrintBulkClinicalForm.HRef = "javascript:showClinicalForm('" + key + "');";

        ancopenpopupaddslot.HRef = "/App/Common/AddSlot.aspx?EventDate=" + eventHostViewData.EventDate.ToShortDateString() + "&keepThis=true&TB_iframe=true&width=295&height=140&modal=true";

        Session["EventID"]     = eventHostViewData.EventId;
        ViewState["EventDate"] = eventHostViewData.EventDate;
        ViewState["EventName"] = eventHostViewData.Name;

        Session["EventDate"] = eventHostViewData.EventDate;
        Session["EventName"] = eventHostViewData.Name;

        if (Convert.ToDateTime(eventHostViewData.EventDate).Date > DateTime.Now.Date)
        {
            aResultStatus.Visible = false;
            //if (!eventPodDetails.IsTeamConfiguredOnEventDay) spIsTeamConfigured.Style[System.Web.UI.HtmlTextWriterStyle.Display] = "none";
        }
        else
        {
            //if (!eventPodDetails.IsTeamConfiguredOnEventDay) spIsTeamConfigured.Style[System.Web.UI.HtmlTextWriterStyle.Display] = "block";

            long shell = IoC.Resolve <ISessionContext>().UserSession.CurrentOrganizationRole.RoleId;
            if (shell == (int)Roles.FranchisorAdmin)
            {
                aResultStatus.HRef = "/App/Franchisor/EventCustomerResult.aspx?AllRecordsEventID=" + eventHostViewData.EventId;
            }
            else
            {
                aResultStatus.HRef = "/App/Franchisee/FranchiseeEventCustomerResult.aspx?AllRecordsEventID=" + eventHostViewData.EventId;
            }
        }

        speventdate.InnerText         = Convert.ToDateTime(eventHostViewData.EventDate).ToShortDateString();
        speventloc.InnerHtml          = eventHostViewData.StreetAddressLine1 + ", " + eventHostViewData.City + ", " + eventHostViewData.State + ", " + eventHostViewData.Zip;
        sphostphone.InnerText         = commonCode.FormatPhoneNumberGet(eventPodDetails.Host.PhoneOffice);
        ViewState["HostName"]         = eventHostViewData.OrganizationName;
        ViewState["HostAddress"]      = eventHostViewData.StreetAddressLine1;
        ViewState["HostCityStateZip"] = eventHostViewData.City + " " + eventHostViewData.State + " " + eventHostViewData.Zip;

        Session["HostName"]         = eventHostViewData.OrganizationName;
        Session["HostAddress"]      = eventHostViewData.StreetAddressLine1;
        Session["HostCityStateZip"] = eventHostViewData.City + " " + eventHostViewData.State + " " + eventHostViewData.Zip;

        spBPEIPDeposit.InnerText = decimal.Round((eventMetricsViewData.CashRevenue + eventMetricsViewData.CheckRevenue), 2).ToString();

        spBPCashPayment.InnerText   = decimal.Round(eventMetricsViewData.CashRevenue, 2).ToString();
        spBPCardPayment.InnerText   = decimal.Round(eventMetricsViewData.ChargeCardRevenue, 2).ToString();
        spBPCheckPayment.InnerText  = decimal.Round(eventMetricsViewData.CheckRevenue, 2).ToString();
        spBPeCheckPayment.InnerText = decimal.Round(eventMetricsViewData.ECheckRevenue, 2).ToString();
        decimal totalRevenue = eventMetricsViewData.ChargeCardRevenue + eventMetricsViewData.CheckRevenue +
                               eventMetricsViewData.CashRevenue + eventMetricsViewData.ECheckRevenue +
                               eventMetricsViewData.GiftCertificateRevenue +
                               eventMetricsViewData.UnPaidExcluedeNoShowRevenue;

        spBPTotalPayment.InnerText = decimal.Round(totalRevenue, 2).ToString();
        spBPEventID.InnerText      = eventHostViewData.EventId.ToString();

        lnkBPRegCustomer.Text          = eventMetricsViewData.RegisteredCustomersCount.ToString();
        spBPCanceledCustomer.InnerHtml = eventMetricsViewData.CancelledCustomersCount.ToString();
        lnkBPNoshowCustomer.Text       = eventMetricsViewData.NoShowCustomersCount.ToString();
        lnkBPPaidCustomer.Text         = eventMetricsViewData.PaidCustomersCount.ToString();
        lnkBPUnpaidCustomer.Text       = eventMetricsViewData.UnPaidCount.ToString();
        lnkBPActCustomer.Text          = eventMetricsViewData.AttendedCustomersCount.ToString();
        lnkBPCardPaymentCount.Text     = eventMetricsViewData.ChargeCardCount.ToString();
        lnkBPCashPayment.Text          = eventMetricsViewData.CashCount.ToString();
        lnkBPCheckPayment.Text         = eventMetricsViewData.CheckCount.ToString();
        lnkBPeCheckPayment.Text        = eventMetricsViewData.ECheckCount.ToString();

        spPhoneCount.InnerText     = decimal.Round(eventMetricsViewData.PhonePayments, 2).ToString();
        lnkPhoneCount.Text         = eventMetricsViewData.PhonePaymentCount.ToString();
        spINetCount.InnerText      = decimal.Round(eventMetricsViewData.InternetPayments, 2).ToString();
        lnkInetCount.Text          = eventMetricsViewData.InternetPaymentCount.ToString();
        spOnsiteCount.InnerText    = decimal.Round(eventMetricsViewData.OnsitePayments, 2).ToString();
        lnkOnsiteCount.Text        = eventMetricsViewData.OnsitePaymentCount.ToString();
        spUpgradeCount.InnerText   = decimal.Round(eventMetricsViewData.UpGradePayments, 2).ToString();
        lnkUpgradeCount.Text       = eventMetricsViewData.UpGradePaymentCount.ToString();
        spDowngradeCount.InnerText = Convert.ToString(decimal.Round((eventMetricsViewData.DownGradePayments < 0 ? eventMetricsViewData.DownGradePayments * -1 : eventMetricsViewData.DownGradePayments), 2));
        lnkDowngradeCount.Text     = eventMetricsViewData.DownGradePaymentCount.ToString();

        //TODO: Need to filter customers paid by GC
        // added giftCertificate
        _spnGcPaymentTotal.InnerText = decimal.Round(eventMetricsViewData.GiftCertificateRevenue, 2).ToString();
        _lnkGcPaymentCount.Text      = eventMetricsViewData.GiftCertificateCount.ToString();

        sphostname.InnerText = eventHostViewData.OrganizationName;
        agmap.HRef           = "http://maps.google.com/maps?f=q&hl=en&geocode=&q=" + eventHostViewData.StreetAddressLine1 + "," + eventHostViewData.City + "," + eventHostViewData.State + "," + eventHostViewData.Zip + "&ie=UTF8&z=16";

        string poddetailstring = "N/A";

        foreach (EEventPod objeventpod in eventPodDetails.EventPod)
        {
            if (poddetailstring == "N/A")
            {
                poddetailstring = "";
            }

            string strpodteam        = "";
            string strpoddescription = "";
            string vandescription    = "";

            strpoddescription = "<p class='roundarrowpopuprow_ecl'>Processing Capacity of " + objeventpod.Pod.PodProcessingCapacity.ToString() + " </p>";
            vandescription    = "<p class='roundarrowpopuprow_ecl'> Vehicle: " + objeventpod.Pod.Van.Name + "," + objeventpod.Pod.Van.Make + " (" + objeventpod.Pod.Van.VIN + ") </p>";

            foreach (EFranchiseeFranchiseeUser objfranchiseefruser in objeventpod.Pod.TeamIDList)
            {
                strpodteam += "&bull; &nbsp;" + objfranchiseefruser.FranchiseeUser.User.FirstName + " " + objfranchiseefruser.FranchiseeUser.User.MiddleName + " " + objfranchiseefruser.FranchiseeUser.User.LastName + "(" + objfranchiseefruser.RoleType + ")(" + objfranchiseefruser.FranchiseeFranchiseeUserID + ")<br />";
            }

            string currentpod = "<div class='maindiv_roundmbox_ecl'><div class='innerdiv_roundmbox'><div class='lefttop_roundmbox'><img src='/App/Images/specer.gif' width='254' height='15' /></div><div class='midinner_roundmbox'>";
            currentpod += "<p class='headertxt_roundmbox_ecl'>Pod Description</p><div class='divinnerbody_mbox'>";
            currentpod += strpoddescription;
            currentpod += "<p><img src='/App/Images/specer.gif' width='220' height='5' /></p>" + vandescription;
            currentpod += "<p><img src='/App/Images/specer.gif' width='220' height='5' /></p><p class='roundarrowpopuprow_ecl'><u>Team Detail</u></p>";
            currentpod += "<p><img src='/App/Images/specer.gif' width='220' height='5' /></p><div class='roundarrowpopuprow_ecl'>";
            currentpod += strpodteam + "</div></div></div><div class='roundcornerbot_roundmbox'>";
            currentpod += "<img src='/App/Images/specer.gif' width='254' height='15' /></div></div></div>";

            poddetailstring = poddetailstring + objeventpod.Pod.Name + "<a href='javascript:void(0)' class='apd'> (More Info) <span class='tooltip'> " + currentpod + " </span> </a>";

            aConfigureTeam.HRef = "javascript:OpenPopUp('/App/Franchisee/Technician/TeamConfiguration.aspx?EventID=" + eventHostViewData.EventId + "&PodID=" + objeventpod.Pod.PodID + "&EventDate=" + eventHostViewData.EventDate.ToShortDateString() + "');";
        }
        sppoddetail.InnerHtml = poddetailstring;

        // BEGIN added upgrade/downgrade story(#7548)
        int totalCustomer = (eventMetricsViewData.PaidCustomersCount + eventMetricsViewData.UnPaidCount) - eventMetricsViewData.NoShowCustomersCount;

        _lnkAverageCustomers.Text = totalCustomer > 0 ? totalCustomer.ToString() : "0";

        _spnAverageRevenueAmount.InnerHtml = totalCustomer > 0
                                        ? decimal.Round((totalRevenue / totalCustomer), 2).ToString()
                                        : "0.00";

        _spnUnpaidTotal.InnerHtml = decimal.Round(eventMetricsViewData.UnPaidExcluedeNoShowRevenue, 2).ToString();
        _lnkUnpaidCount.Text      = eventMetricsViewData.UnPaidExcluedeNoShowCount.ToString();

        // END added upgrade/downgrade story(#7548)

        // Added HipaaStatus
        decimal _HipaapercentageDecimal;

        if (eventMetricsViewData.HipaaSignedCount > 0)
        {
            _HipaapercentageDecimal = Math.Round(
                Convert.ToDecimal(eventMetricsViewData.HipaaSignedCount) /
                Convert.ToDecimal(eventMetricsViewData.HipaaSignedCount + eventMetricsViewData.HipaaUnSignedCount) * 100,
                2);

            if (_HipaapercentageDecimal > 0)
            {
                _spnHippaStatus.InnerText = Convert.ToString(_HipaapercentageDecimal) + "% " + "(" +
                                            eventMetricsViewData.HipaaSignedCount + "/" +
                                            (eventMetricsViewData.HipaaSignedCount + eventMetricsViewData.HipaaUnSignedCount) + ")";
            }
        }
        else
        {
            _spnHippaStatus.InnerText = "0% (0/0)";
        }
    }
Ejemplo n.º 19
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IAntiforgery antiForgery)
        {
            app.UseHttpsRedirection()
            .UseSession()
            .UseFileServer()
            .UseCookiePolicy()
            .UseCors("CorsPolicy")
            .UseAuthentication()
            .UseAuthorization()
            .Use(next => context =>
            {
                var tokens = antiForgery.GetAndStoreTokens(context);
                context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                                                new CookieOptions {
                    HttpOnly = false
                });
                antiForgery.ValidateRequestAsync(context);
                return(next(context));
            })
            .UseRouting()
            .UseEndpoints(endpoints => { endpoints.MapControllers(); });

            // The following code is for demo purposes only.
            // In a production environment, only database initialization and
            // method blockchainService.InitializeBlockchain() are needed.

            using var serviceScope = app.ApplicationServices.CreateScope();
            var userService       = serviceScope.ServiceProvider.GetService <IUserService>();
            var blockchainService = serviceScope.ServiceProvider.GetService <IBlockchainService>();
            var companyService    = serviceScope.ServiceProvider.GetService <ICompanyService>();
            var vesselService     = serviceScope.ServiceProvider.GetService <IVesselService>();

            // Set admin for demo purposes
            if (userService.FindByPosition("admin") == null)
            {
                userService.Insert(new User
                {
                    PublicKey            = "efa3036945807cc349ae55b2b503d8832c0250bb8782d32b74af6a63850fedaa",
                    FirstName            = "Admin",
                    LastName             = "Admin",
                    Email                = "*****@*****.**",
                    Position             = "admin",
                    Enabled              = true,
                    CorrespondingIndices = new Dictionary <string, string>()
                });
            }

            // Set plain user for demo purposes
            var testUser = new User
            {
                PublicKey            = "d083057717d54238428da204ba14ddb3ef287a7aa0e3abe1f9ad6c7874bfc446",
                FirstName            = "John",
                LastName             = "Doe",
                Email                = "*****@*****.**",
                Company              = "1234567890",
                Position             = "legalEngineer",
                Enabled              = true,
                CorrespondingIndices = new Dictionary <string, string>()
            };

            // Set company vessels registry manager for demo purposes
            if (userService.FindByPosition("companyVesselsRegistryManager") == null)
            {
                userService.Insert(new User {
                    PublicKey            = "0783582ff507282b0ae01d2e1551530f347acb59180aabbbcc5ff359a7c3c323",
                    FirstName            = "Bernard",
                    LastName             = "Johnson",
                    Email                = "*****@*****.**",
                    Company              = "1234567890",
                    Position             = "companyVesselsRegistryManager",
                    Enabled              = true,
                    CorrespondingIndices = new Dictionary <string, string>()
                });
            }

            // Insert dummy data (vessel) for demo purposes
            if (vesselService.FindByImoNumber("1234567890") == null)
            {
                vesselService.Insert(new Vessel()
                {
                    ImoNumber         = "1234567890",
                    Name              = "e-Harmony",
                    Flag              = "US",
                    Company           = "1234567890",
                    YearBuilt         = "2019",
                    Dwt               = "300000",
                    UnderConstruction = false
                });
            }

            //Set company for demo purposes
            if (companyService.FindByName("Maran Tankers Management Inc.") == null)
            {
                companyService.Insert(new Company
                {
                    RegistryNumber = "1234567890",
                    Name           = "Maran Tankers Management Inc.",
                    Type           = "tankerManagementServices",
                    Email          = "*****@*****.**",
                    Address        = "Maran Avenue 123, New York 133 00, NY, United States",
                    Vessels        = new LinkedList <string>(new[] { vesselService.FindByName("e-Harmony").Id })
                });
            }

            var dbUser = userService.FindByPublicKey("d083057717d54238428da204ba14ddb3ef287a7aa0e3abe1f9ad6c7874bfc446");

            // If there is already a user with this public key
            if (dbUser != null)
            {
                testUser = dbUser;
            }
            else
            {
                userService.Insert(testUser);
            }

            blockchainService.InitializeBlockchain();

            // Insert dummy data (contract) for demo purposes
            if (blockchainService.FindLastBlock().Index != "0")
            {
                return;
            }
            var essentials = new Dictionary <string, dynamic>
            {
                ["type"]     = "timeCharter",
                ["preamble"] = "THIS TIME CHARTER, made and concluded in the datetime mentioned above between the parties described in the contracting parties section, shall be performed subject to all the terms and conditions included in the clauses section along with any additional clauses and addenda.",
                ["vessel"]   = "1234567890"
            };
            var clauses = new LinkedList <Clause>(new[] { FixedClausesFactory.GetOffHireClause() });
            var contractNoSignatures = JsonConvert.SerializeObject(new Contract("Contract", "timeCharter", essentials, clauses));
            var signature1           = new Dictionary <string, dynamic>
            {
                ["signature"]  = CryptographyService.Sign(contractNoSignatures, "d0b2df0582f262e50dccc9f3586ded1d0560ff4b46db82806a74b2493e9b92ad"),
                ["signer"]     = "d083057717d54238428da204ba14ddb3ef287a7aa0e3abe1f9ad6c7874bfc446",
                ["onBehalfOf"] = "d083057717d54238428da204ba14ddb3ef287a7aa0e3abe1f9ad6c7874bfc446"
            };
            var signature2 = new Dictionary <string, dynamic>
            {
                ["signature"]  = CryptographyService.Sign(contractNoSignatures, "d0b2df0582f262e50dccc9f3586ded1d0560ff4b46db82806a74b2493e9b92ad"),
                ["signer"]     = "d083057717d54238428da204ba14ddb3ef287a7aa0e3abe1f9ad6c7874bfc446",
                ["onBehalfOf"] = "d083057717d54238428da204ba14ddb3ef287a7aa0e3abe1f9ad6c7874bfc446"
            };

            essentials["signatures"] = new List <dynamic> {
                signature1, signature2
            };
            var contract      = new Contract("Contract", "timeCharter", essentials, clauses);
            var encryptedData = CryptographyService.Encrypt(JsonConvert.SerializeObject(contract));
            var newLastBlock  = blockchainService.FindLastBlock();

            blockchainService.InsertBlock(new Block((Convert.ToInt64(newLastBlock.Index) + 1).ToString(), encryptedData[0], newLastBlock.Hash));
            var encryptedSecret          = CryptographyService.EncryptWithPublicKey(encryptedData[1], testUser.PublicKey);
            var userCorrespondingIndices = testUser.CorrespondingIndices;

            userCorrespondingIndices[(Convert.ToInt64(newLastBlock.Index) + 1).ToString()] = encryptedSecret;
            testUser.CorrespondingIndices = userCorrespondingIndices;
            userService.Update(testUser);
        }