public void UpdateCustomerPassword(string username, string oldPassword, string newPassword)
        {
            Customer customer = AuthoriseRequest();

            if (customer.CustomerUsername == username)
            {
                if (PasswordHash.Hash(oldPassword, customer.Salt) != customer.CustomerPassword)
                {
                    throw new ApplicationException("The existing password did not match when attempting a password update.");
                }
                else
                {
                    logger.Debug("Updating customer password for " + customer.CustomerUsername);
                    //customer.CustomerPassword = newPassword;

                    // Hash the password.
                    string salt = PasswordHash.GenerateSalt();
                    customer.CustomerPassword = PasswordHash.Hash(newPassword, salt);
                    customer.Salt             = salt;

                    CRMCustomerPersistor.Update(customer);
                }
            }
            else
            {
                throw new ApplicationException("You are not authorised to update customer password for username " + username + ".");
            }
        }
Пример #2
0
        //public async Task<IResponseModel> RegisterClientAsync(ClientModel model)
        //{
        //    try
        //    {
        //        var client = new Client
        //        {
        //            Id = Guid.NewGuid(),
        //            Email = model.Email,
        //            ApiKey = Guid.NewGuid()
        //        };

        //        _db.Clients.Add(client);
        //        await _db.SaveChangesAsync();

        //        _response.Status = true;
        //        _response.Message = "Client registration successful.";

        //        return _response;
        //    }
        //    catch (Exception ex)
        //    {
        //        _response.Status = false;
        //        _response.Message = "Client registration error.";

        //        return _response;
        //    }
        //}

        //public async Task<ClientModel> VerifyClientAsync(ClientModel model)
        //{
        //    try
        //    {
        //        var clientInfo = await _db.Clients.Where(u => u.Email == model.Email && u.ApiKey == model.ApiKey).SingleOrDefaultAsync();

        //        if (clientInfo == null) return null;

        //        return new ClientModel
        //        {
        //            Email = clientInfo.Email,
        //            ClientId = clientInfo.Id
        //        };
        //    }
        //    catch (Exception ex)
        //    {
        //        throw;
        //    }
        //}

        //public TokenModel GenerateJwt(ClientModel model)
        //{
        //    var token = new JwtTokenBuilder(_config);

        //    return new TokenModel
        //    {
        //        AccessToken = token.GenerateToken(),
        //        Email = model.Email
        //    };
        //}
        #endregion

        #region User Authentication
        public async Task <IResponseModel> RegisterUserAsync(IUserModel model)
        {
            try
            {
                var salt         = PasswordHash.GenerateSalt();
                var passwordHash = PasswordHash.ComputeHash(model.Password, salt);

                var user = new User
                {
                    Id = Guid.NewGuid(),
                    //ClientId = ClientAppHelper.ClientApp,
                    Username = model.Username,
                    Password = Convert.ToBase64String(passwordHash),
                    Salt     = Convert.ToBase64String(salt)
                };

                _db.Users.Add(user);
                await _db.SaveChangesAsync();

                _response.Status  = true;
                _response.Message = "User registration successful.";

                return(_response);
            }
            catch (Exception ex)
            {
                _response.Status  = false;
                _response.Message = "User registration error.";

                return(_response);
            }
        }
Пример #3
0
        /// <summary>
        /// Generates a new password Salt.
        /// </summary>
        /// <returns>New password Salt as a byte array.</returns>
        public byte[] GetNewPasswordSalt()
        {
            byte[] Salt = PasswordHash.GenerateSalt();

            //TPasswordHelper.LogByteArrayContents(Salt, "TPasswordHashingScheme_V1 - Salt");

            return(Salt);
        }
Пример #4
0
        /// <summary>
        ///     Generate a new random key.
        /// </summary>
        /// <returns>A random key.</returns>
        private static Key GenerateNewKey()
        {
            var keyPair = PublicKeyBox.GenerateKeyPair();
            var key     = new Key
            {
                KeyType    = KeyType.Lageant,
                PrivateKey = keyPair.PrivateKey,
                PublicKey  = keyPair.PublicKey,
                KeyId      = SodiumCore.GetRandomBytes(8),
                KeySalt    = PasswordHash.GenerateSalt(),
                KeyNonce   = PublicKeyBox.GenerateNonce()
            };

            return(key);
        }
Пример #5
0
        public string GenerateAdminPassword(Admin admin, Guid userId)
        {
            if (userId == null)
            {
                throw new Exception(ErrorConstants.REQUIRED_FIELD_EMPTY);
            }
            if (admin == null || admin.type != (int)BillingEnums.USER_TYPE.SUPER_ADMIN)
            {
                throw new Exception(ErrorConstants.NO_PREVILAGE);
            }

            try
            {
                var updateAdmin = GetAdminById(userId);
                if (updateAdmin == null)
                {
                    throw new Exception(ErrorConstants.ADMIN_NOT_FOUND);
                }

                var password = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                updateAdmin.salt     = PasswordHash.GenerateSalt();
                updateAdmin.password = PasswordHash.CreateHash(password, updateAdmin.salt);

                var adminUpdate = new Dictionary <string, object>();
                adminUpdate[ConstAdmin.SALT]     = updateAdmin.salt;
                adminUpdate[ConstAdmin.PASSWORD] = updateAdmin.password;

                var elasticClient = GetElasticClient();

                var updateResponse = elasticClient.Update <Admin, object>(u => u
                                                                          .Index(ElasticMappingConstants.INDEX_NAME)
                                                                          .Type(ElasticMappingConstants.TYPE_ADMIN)
                                                                          .Id(updateAdmin.id.ToString())
                                                                          .Doc(adminUpdate));

                if (!updateResponse.RequestInformation.Success)
                {
                    throw new Exception(ErrorConstants.PROBLEM_OCCURED_WHILE_GENERATING_PASSWORD);
                }

                return(password);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Пример #6
0
        public void ChangePassword(string oldPassword, string newPassword)
        {
            Customer customer = this.ObjectContext.Customers.Where(x => x.Name == this.ServiceContext.User.Identity.Name).First();

            if (PasswordHash.Hash(oldPassword, customer.Salt) != customer.CustomerPassword)
            {
                throw new ApplicationException("The old password was not correct. Password was not updated.");
            }
            else
            {
                //customer.CustomerPassword = newPassword;

                string salt = PasswordHash.GenerateSalt();
                customer.CustomerPassword = PasswordHash.Hash(newPassword, salt);
                customer.Salt             = salt;

                this.ObjectContext.SaveChanges();
            }
        }
        public async Task AccountService_RegisterUserAsync_Test()
        {
            try
            {
                using (db = new DatabaseContext(dbBuilder.Options))
                {
                    var userModel = new UserModel
                    {
                        Username  = null,
                        Password  = "******",
                        FirstName = "Test",
                        LastName  = "Test"
                    };

                    var salt         = PasswordHash.GenerateSalt();
                    var passwordHash = PasswordHash.ComputeHash(userModel.Password, salt);

                    var user = new ApplicationUser
                    {
                        Id             = Guid.NewGuid(),
                        ClientId       = config["AppConfiguration:Audience"],
                        Email          = userModel.Username,
                        Password       = Convert.ToBase64String(passwordHash),
                        FirstName      = userModel.FirstName,
                        LastName       = userModel.LastName,
                        EmailConfirmed = false,
                        DateRegistered = DateTime.UtcNow,
                        Salt           = Convert.ToBase64String(salt)
                    };

                    db.Users.Add(user);
                    var result = await db.SaveChangesAsync();

                    Assert.IsTrue(result == 1);
                }
            }
            catch (Exception ex)
            {
                logService.Log("Register User", ex.InnerException.Message, ex.Message, ex.StackTrace);
                Assert.Fail(ex.Message);
            }
        }
Пример #8
0
        public void AddSuperAdmin()
        {
            var elasticClient = GetElasticClient();

            var termFilter = new TermFilter()
            {
                Field = ConstAdmin.TYPE,
                Value = (short)BillingEnums.USER_TYPE.SUPER_ADMIN
            };

            try
            {
                var response = elasticClient.Search <Admin>(a => a
                                                            .Index(ElasticMappingConstants.INDEX_NAME)
                                                            .Type(ElasticMappingConstants.TYPE_ADMIN)
                                                            .Filter(termFilter)
                                                            .Take(1));

                if (response.Total == 0)
                {
                    var salt  = PasswordHash.GenerateSalt();
                    var admin = new Admin()
                    {
                        id         = Guid.NewGuid(),
                        username   = AppConstants.SUPER_ADMIN_USER_NAME,
                        salt       = salt,
                        password   = PasswordHash.CreateHash(AppConstants.SUPER_ADMIN_PASSWORD, salt),
                        type       = (int)BillingEnums.USER_TYPE.SUPER_ADMIN,
                        created_at = DateTime.UtcNow
                    };

                    var create = elasticClient.Index <Admin>(admin, i => i
                                                             .Index(ElasticMappingConstants.INDEX_NAME)
                                                             .Type(ElasticMappingConstants.TYPE_ADMIN));
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.GetBaseException().Message);
            }
        }
Пример #9
0
        public async Task <IResponseModel> RegisterUserAsync(IUserModel model)
        {
            try
            {
                var salt         = PasswordHash.GenerateSalt();
                var passwordHash = PasswordHash.ComputeHash(model.Password, salt);

                var user = new ApplicationUser
                {
                    Id             = Guid.NewGuid(),
                    ClientId       = _config["AppConfiguration:Audience"],
                    Email          = model.Username,
                    Password       = Convert.ToBase64String(passwordHash),
                    FirstName      = model.FirstName,
                    LastName       = model.LastName,
                    EmailConfirmed = false,
                    DateRegistered = DateTime.UtcNow,
                    Salt           = Convert.ToBase64String(salt)
                };

                _db.Users.Add(user);
                await _db.SaveChangesAsync();

                _response.Status  = true;
                _response.Message = "Registration Successful.";

                return(_response);
            }
            catch (Exception ex)
            {
                _loggerService.Log("Register User", ex.InnerException.Message, ex.Message, ex.StackTrace);

                _response.Status  = false;
                _response.Message = "Registration Error.";

                return(_response);
            }
        }
        public ActionResult Create(LOGIN newuser)
        {
            if (Request.IsAuthenticated)
            {
                using (trackerEntities db = new trackerEntities())
                {
                    PasswordHash pass = new PasswordHash();
                    pass.Salt = pass.GenerateSalt();

                    newuser.userID        = (int)TempData["u2"];
                    newuser.password      = (string)TempData["pass"];
                    newuser.password      = pass.GetHash(newuser.password, pass.Salt);
                    newuser.password_salt = Convert.ToBase64String(pass.Salt);
                    //int hash = newuser.password.GetHashCode();
                    //newuser.password_salt = hash; //password salt needs to be int ??

                    USER User = (USER)TempData["userModel"];
                    db.USERs.Add(User);
                    //db.SaveChanges();
                    if (User.user_type != "Volunteer")
                    {
                        PAID_STAFF pAID_STAFF = (PAID_STAFF)TempData["paidStaffModel"];
                        db.PAID_STAFF.Add(pAID_STAFF);
                        //db.SaveChanges();
                    }
                    db.LOGINs.Add(newuser);
                    db.SaveChanges();
                }
                ModelState.Clear();
                ViewBag.SuccessMessage = "Registration Success!";
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                return(RedirectToAction("Index", "Home"));
            }
            //return View("Create", new LOGIN());
        }
Пример #11
0
 public void TestGenerateSalt()
 {
     Assert.AreEqual(32, PasswordHash.GenerateSalt().Length);
 }
Пример #12
0
        static void Test()
        {
            Console.WriteLine("safe RNG");
            foreach (var i in Enumerable.Range(0, 10))
            {
                Console.WriteLine(Convert.ToBase64String(GenerateRandomNumber(32)));;
            }

            const string message = "Secret message";

            Console.WriteLine($"hashes of '{message}'");
            Console.WriteLine($"MD5: {Convert.ToBase64String(CalculateMd5(Encoding.UTF8.GetBytes(message)))}");
            Console.WriteLine($"SHA1: {Convert.ToBase64String(CalculateSha1(Encoding.UTF8.GetBytes(message)))}");
            Console.WriteLine($"SHA256: {Convert.ToBase64String(CalculateSha256(Encoding.UTF8.GetBytes(message)))}");
            Console.WriteLine($"SHA512: {Convert.ToBase64String(CalculateSha512(Encoding.UTF8.GetBytes(message)))}");

            const string message2 = "Secret Message";

            Console.WriteLine($"hashes of '{message2}'");
            Console.WriteLine($"MD5: {Convert.ToBase64String(CalculateMd5(Encoding.UTF8.GetBytes(message2)))}");
            Console.WriteLine($"SHA1: {Convert.ToBase64String(CalculateSha1(Encoding.UTF8.GetBytes(message2)))}");
            Console.WriteLine($"SHA256: {Convert.ToBase64String(CalculateSha256(Encoding.UTF8.GetBytes(message2)))}");
            Console.WriteLine($"SHA512: {Convert.ToBase64String(CalculateSha512(Encoding.UTF8.GetBytes(message2)))}");

            Console.WriteLine($"HMACs of '{message}'");
            var key = Hmac.GenerateKey();

            Console.WriteLine($"HmacMd5: {Convert.ToBase64String(Hmac.ComputeHmacMd5(key, Encoding.UTF8.GetBytes(message)))}");
            Console.WriteLine($"HmacSha1: {Convert.ToBase64String(Hmac.ComputeHmacSha1(key, Encoding.UTF8.GetBytes(message)))}");
            Console.WriteLine($"HmacSha256: {Convert.ToBase64String(Hmac.ComputeHmacSha256(key, Encoding.UTF8.GetBytes(message)))}");
            Console.WriteLine($"HmacSha512: {Convert.ToBase64String(Hmac.ComputeHmacSha512(key, Encoding.UTF8.GetBytes(message)))}");

            Console.WriteLine("Hash password with salt");
            const string password = "******";
            var          salt     = PasswordHash.GenerateSalt();

            Console.WriteLine($"Salt: {Convert.ToBase64String(salt)}");
            Console.WriteLine(Convert.ToBase64String(PasswordHash.HashPasswordWithSalt(Encoding.UTF8.GetBytes(password), salt)));

            Console.WriteLine("Hash same password with PBKDF2");
            Console.WriteLine(Convert.ToBase64String(PasswordHash.HashPasswordPbkdf2(Encoding.UTF8.GetBytes(password), salt, 150_000)));

            Console.WriteLine("DES example on 'Lorem Ipsum'");
            const string messageSymmetric = "Lorem ispum dolor sit amet.";
            var          ivDes            = GenerateRandomNumber(8);
            var          keyDes           = GenerateRandomNumber(8);
            var          encryptedDes     = EncryptDes(Encoding.UTF8.GetBytes(messageSymmetric), keyDes, ivDes);
            var          decryptedDes     = DecryptDes(encryptedDes, keyDes, ivDes);

            Console.WriteLine($"EncryptedDES: {Convert.ToBase64String(encryptedDes)}");
            Console.WriteLine($"DecryptedDES: {Encoding.UTF8.GetString(decryptedDes)}");

            Console.WriteLine("TripleDES example on Lorem Ipsum");
            var keyTripleDes       = GenerateRandomNumber(24);
            var ivTripleDes        = GenerateRandomNumber(8);
            var encryptedTripleDes = EncryptTripleDes(Encoding.UTF8.GetBytes(messageSymmetric), keyTripleDes, ivTripleDes);
            var decryptedTripleDes = DecryptTripleDes(encryptedTripleDes, keyTripleDes, ivTripleDes);

            Console.WriteLine($"EncryptedTripleDES: {Convert.ToBase64String(encryptedTripleDes)}");
            Console.WriteLine($"DecryptedTripleDES: {Encoding.UTF8.GetString(decryptedTripleDes)}");

            Console.WriteLine("AES example on Lorem Ipsum");
            var keyAes       = GenerateRandomNumber(32);
            var ivAes        = GenerateRandomNumber(16);
            var encryptedAes = EncryptAes(Encoding.UTF8.GetBytes(messageSymmetric), keyAes, ivAes);
            var decryptedAes = DecryptAes(encryptedAes, keyAes, ivAes);

            Console.WriteLine($"EncryptedAES: {Convert.ToBase64String(encryptedAes)}");
            Console.WriteLine($"DecryptedAES: {Encoding.UTF8.GetString(decryptedAes)}");

            Console.WriteLine("RSA in memory example on Lorem Ipsum");
            var inMemoryAsymmetricOptions = new AsymmetricCryptoServiceOptions
            {
                KeySize = KeySize.KeySize2048,
            };
            var asymmetricInMemoryCryptoProvider = new AsymmetricCryptoServiceBuilder()
                                                   .WithOptions(inMemoryAsymmetricOptions).WithKeyStorageOption(KeyStorageOption.InMemory).Build();
            var encryptedRsa = asymmetricInMemoryCryptoProvider.Encrypt(Encoding.UTF8.GetBytes(messageSymmetric));
            var decryptedRsa = asymmetricInMemoryCryptoProvider.Decrypt(encryptedRsa);

            Console.WriteLine($"Encrypted RSA: {Convert.ToBase64String(encryptedRsa)}");
            Console.WriteLine($"Decrypted RSA: {Encoding.UTF8.GetString(decryptedRsa)}");

            Console.WriteLine("RSA XML example on Lorem Ipsum");
            var xmlAsymmetricOptions = new AsymmetricCryptoServiceOptions
            {
                KeySize = KeySize.KeySize2048,
                XmlPrivateKeyFilePath = Path.Combine(Directory.GetCurrentDirectory(), "privateKey.xml"),
                XmlPublicKeyFilePath  = Path.Combine(Directory.GetCurrentDirectory(), "publicKey.xml"),
            };
            var asymmetricXmlCryptoProvider = new AsymmetricCryptoServiceBuilder()
                                              .WithOptions(xmlAsymmetricOptions).WithKeyStorageOption(KeyStorageOption.InMemory).Build();

            encryptedRsa = asymmetricXmlCryptoProvider.Encrypt(Encoding.UTF8.GetBytes(messageSymmetric));
            decryptedRsa = asymmetricXmlCryptoProvider.Decrypt(encryptedRsa);
            Console.WriteLine($"Encrypted RSA: {Convert.ToBase64String(encryptedRsa)}");
            Console.WriteLine($"Decrypted RSA: {Encoding.UTF8.GetString(decryptedRsa)}");

            Console.WriteLine("RSA CSP example on Lorem Ipsum");
            var cspAsymmetricOptions = new AsymmetricCryptoServiceOptions
            {
                CspParameters = new CspParameters(1)
                {
                    KeyContainerName = "AppliedCryptographyTest",
                    ProviderName     = "Microsoft Strong Cryptographic Provider",
                    Flags            = CspProviderFlags.UseMachineKeyStore,
                },
                KeySize = KeySize.KeySize2048,
            };
            var asymmetricCspCryptoProvider = new AsymmetricCryptoServiceBuilder().WithOptions(cspAsymmetricOptions)
                                              .WithKeyStorageOption(KeyStorageOption.Csp).Build();

            encryptedRsa = asymmetricCspCryptoProvider.Encrypt(Encoding.UTF8.GetBytes(messageSymmetric));
            decryptedRsa = asymmetricCspCryptoProvider.Decrypt(encryptedRsa);
            Console.WriteLine($"Encrypted RSA: {Convert.ToBase64String(encryptedRsa)}");
            Console.WriteLine($"Decrypted RSA: {Encoding.UTF8.GetString(decryptedRsa)}");

            Console.WriteLine("DigitalSignature InMemory example on LoremIpsum");
            var digitalSignatureInMemoryOptions = new DigitalSignatureProviderOptions
            {
                HashAlgorithm = DigitalSignatureHashAlgorithm.SHA512,
                KeySize       = KeySize.KeySize2048,
            };
            var digitalSignatureInMemoryProvider = new DigitalSignatureProviderBuilder()
                                                   .WithOptions(digitalSignatureInMemoryOptions).WithKeyStorageOption(KeyStorageOption.InMemory).Build();
            var signedHash = digitalSignatureInMemoryProvider.Sign(CalculateSha512(Encoding.UTF8.GetBytes(messageSymmetric)));

            Console.WriteLine($"Signed hash: {Convert.ToBase64String(signedHash)}");
            var compareHash = CalculateSha512(Encoding.UTF8.GetBytes(messageSymmetric));

            Console.WriteLine($"Compare hashes: {digitalSignatureInMemoryProvider.Verify(signedHash, compareHash).ToString()}");
            compareHash[0] = Byte.MaxValue;
            Console.WriteLine($"Compare hashes with tapering: {digitalSignatureInMemoryProvider.Verify(signedHash, compareHash).ToString()}");
        }
Пример #13
0
 /// <summary>Generate a random salt for use with HashPassword.  In addition to the random salt, the salt value
 /// also contains the tuning parameters to use with the scrypt algorithm, as well as the size of the password
 /// hash to generate.</summary>
 /// <param name="saltLengthBytes">The number of bytes of random salt to generate.  The goal for the salt is
 /// to be unique.  16 bytes gives a 2^128 possible salt options, and roughly an N in 2^64 chance of a salt
 /// collision for N salts, which seems reasonable.  A larger salt requires more storage space, but doesn't
 /// affect the scrypt performance significantly.</param>
 /// <param name="N">CPU/memory cost parameter.  Must be a value 2^N.  2^14 (16384) causes a calculation time
 /// of approximately 50-70ms on 2010 era hardware; each successive value (eg. 2^15, 2^16, ...) should
 /// double the amount of CPU time and memory required.</param>
 /// <param name="r">scrypt 'r' tuning parameter</param>
 /// <param name="p">scrypt 'p' tuning parameter (parallelization parameter); a large value of p can increase
 /// computational cost of scrypt without increasing the memory usage.</param>
 /// <param name="hashLengthBytes">The number of bytes to store the password hash in.</param>
 public static string GenerateSalt(uint saltLengthBytes, ulong N, uint r, uint p, uint hashLengthBytes)
 {
     return(PasswordHash.GenerateSalt(saltLengthBytes, N, r, p, hashLengthBytes));
 }
Пример #14
0
 /// <summary>Generate a salt for use with HashPassword, selecting reasonable default values for scrypt
 /// parameters that are appropriate for an interactive login verification workflow.</summary>
 /// <remarks>Uses the default values in DefaultSaltLengthBytes, Default_N, Default_r, Default_r, and
 /// DefaultHashLengthBytes.</remarks>
 public static string GenerateSalt()
 {
     return(PasswordHash.GenerateSalt());
 }
Пример #15
0
        /// <summary>
        ///     Store/Export a key to file.
        /// </summary>
        public async void ExportKeyToFile()
        {
            MainViewError = string.Empty;
            IsWorking     = true;
            string password;

            if (SelectedKey != null)
            {
                var exportKey = new Key
                {
                    PublicKey  = SelectedKey.PublicKey,
                    PrivateKey = SelectedKey.PrivateKey,
                    KeyType    = SelectedKey.KeyType,
                    KeyId      = SelectedKey.KeyId ?? null,
                    KeySalt    = SelectedKey.KeySalt ?? PasswordHash.GenerateSalt(),
                    KeyNonce   = SelectedKey.KeyNonce ?? SecretBox.GenerateNonce()
                };

                var saveFileDialog = new SaveFileDialog
                {
                    OverwritePrompt = true,
                    AddExtension    = true,
                    DefaultExt      = ".lkey"
                };

                if (exportKey.KeyId != null)
                {
                    saveFileDialog.FileName = Utilities.BinaryToHex(exportKey.KeyId);
                }
                var result = saveFileDialog.ShowDialog();
                if (result == true)
                {
                    var filename = saveFileDialog.FileName;
                    try
                    {
                        var win = new PasswordInputViewModel {
                            DisplayName = "Enter a new protection password"
                        };
                        dynamic settings = new ExpandoObject();
                        settings.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                        settings.Owner = GetView();
                        var inputOk = _windowManager.ShowDialog(win, null, settings);
                        if (inputOk == true)
                        {
                            password = win.UserPassword;
                            if (!string.IsNullOrEmpty(password))
                            {
                                var encryptionKey = await Task.Run(() =>
                                {
                                    var tmpKey = new byte[32];
                                    try
                                    {
                                        tmpKey = PasswordHash.ScryptHashBinary(Encoding.UTF8.GetBytes(password),
                                                                               exportKey.KeySalt, PasswordHash.Strength.MediumSlow, 32);
                                    }
                                    catch (OutOfMemoryException)
                                    {
                                        MainViewError = "Could not export key (out of memory).";
                                    }
                                    catch (Exception)
                                    {
                                        MainViewError = "Could not export key.";
                                    }
                                    return(tmpKey);
                                }).ConfigureAwait(true);

                                if (encryptionKey != null)
                                {
                                    exportKey.PrivateKey = SecretBox.Create(exportKey.PrivateKey, exportKey.KeyNonce,
                                                                            encryptionKey);
                                    using (var keyFileStream = File.OpenWrite(filename))
                                    {
                                        Serializer.SerializeWithLengthPrefix(keyFileStream, exportKey,
                                                                             PrefixStyle.Base128,
                                                                             0);
                                    }
                                }
                                else
                                {
                                    MainViewError = "Could not export key (missing encryption key?)";
                                }
                            }
                            else
                            {
                                MainViewError = "Could not export key (missing password)";
                            }
                        }
                    }
                    catch (Exception)
                    {
                        MainViewError = "Could not export key (failure)";
                    }
                }
                else
                {
                    MainViewError = "Could not export key (missing password)";
                }
            }
            IsWorking = false;
        }
Пример #16
0
        // When setting password
        public string EncryptPassword(string password)
        {
            string hashedPassword = PasswordHash.HashPassword(password, PasswordHash.GenerateSalt());

            return(hashedPassword);
        }