public RegistrationApplicationService( IEventStore eventStore,IDomainIdentityService ids, IUserIndexService uniqueness, PasswordGenerator generator) { _eventStore = eventStore; _ids = ids; _uniqueness = uniqueness; _generator = generator; }
public void CreateRegistration( RegistrationId i, RegistrationInfo info, IDomainIdentityService ids, IUserIndexService uniqueness, PasswordGenerator generator) { var problems = new List<string>(); // we do all the checks at registration phase if (uniqueness.IsLoginRegistered(info.ContactEmail)) { problems.Add(string.Format("Email '{0}' is already taken.", info.ContactEmail)); } if (!string.IsNullOrEmpty(info.OptionalUserIdentity)) { if (uniqueness.IsIdentityRegistered(info.OptionalUserIdentity)) { problems.Add(string.Format("Identity '{0}' is already taken.", info.OptionalUserIdentity)); } } var userDisplay = info.OptionalUserDisplay; if (string.IsNullOrEmpty(userDisplay)) { userDisplay = string.Format("{0}", info.CustomerName); } var password = info.OptionalUserPassword; if (string.IsNullOrEmpty(password)) { password = generator.CreatePassword(6); } // TODO: we are checking contact uniqueness, but can use user name var login = info.ContactEmail; if (string.IsNullOrEmpty(login)) { login = info.ContactEmail; } if (problems.Any()) { Apply(new RegistrationFailed(i, info, problems.ToArray())); return; } var id = ids.GetId(); var host = info.Headers.FirstOrDefault(h => h.Key == "UserHostAddress"); var security = new SecurityInfo(new SecurityId(id), login, password, userDisplay, info.OptionalUserIdentity); var customer = new CustomerInfo(new CustomerId(id), info.CustomerName, userDisplay, info.ContactEmail, info.OptionalCompanyPhone, info.OptionalCompanyUrl); Apply(new RegistrationCreated(i, info.CreatedUtc, customer, security)); // if no problems }
public void AddIdentity(IDomainIdentityService ids, PasswordGenerator pwds, string display, string identity) { if (_state.ContainsIdentity(identity)) return; var user = new UserId(ids.GetId()); var token = pwds.CreateToken(); Apply(new SecurityIdentityAdded(_state.Id, user, display, identity, token)); }
public SecurityApplicationService( IEventStore eventStore, IDomainIdentityService ids, PasswordGenerator pwds) { _eventStore = eventStore; _ids = ids; _pwds = pwds; }
internal static Renewal Create(string id, PasswordGenerator generator) { var ret = new Renewal { New = true, Id = string.IsNullOrEmpty(id) ? ShortGuid.NewGuid().ToString() : id, PfxPassword = generator.Generate() }; return(ret); }
public static User Generate() { var user = new User { EmailAddress = EmailAddressGenerator.Generate(), Password = PasswordGenerator.Generate() }; LastGeneratedUser = user; return(user); }
public void user_cant_login_with_wrong_password() { var clock = new Clock(); var passwordStore = new PasswordStore(clock); var passwordGenerator = new PasswordGenerator(passwordStore); var username = "******"; var password = passwordGenerator.GeneratePassword(username); var success = passwordStore.IsPasswordValidForUsername(username, password + "te"); Assert.False(success); }
public void Can_create_user_and_verify() { var clock = new Clock(); var passwordStore = new PasswordStore(clock); var passwordGenerator = new PasswordGenerator(passwordStore); var username = "******"; var password = passwordGenerator.GeneratePassword(username); var success = passwordStore.IsPasswordValidForUsername(username, password); Assert.True(success); }
public Credential(long OwnerId, string listScopes) { this.AccessToken = PasswordGenerator.Generate(length: 40, allowed: Sets.Alphanumerics); this.RefreshToken = PasswordGenerator.Generate(length: 40, allowed: Sets.Alphanumerics); this.OwnerId = OwnerId; this.CreatedAt = DateTime.Now; this.UpdatedAt = DateTime.Now; //this.Scope = CredentialScope.Basic; this.Status = CredentialStatus.Active; this.ExpiredAt = DateTime.Now.AddDays(7); }
public Importer(ILogService log, ILegacyRenewalService legacyRenewal, IRenewalService currentRenewal, LegacyTaskSchedulerService legacyTaskScheduler, TaskSchedulerService currentTaskScheduler, PasswordGenerator passwordGenerator) { _legacyRenewal = legacyRenewal; _currentRenewal = currentRenewal; _log = log; _currentTaskScheduler = currentTaskScheduler; _legacyTaskScheduler = legacyTaskScheduler; _passwordGenerator = passwordGenerator; }
public void Generated_password_lengths_equals_input_length() { for (int i = 1; i <= 50; i++) { string password = PasswordGenerator.Generate(i); password.Length.ShouldBe(i); SecureString securePassword = PasswordGenerator.GenerateSecure(i); securePassword.Length.ShouldBe(i); } }
public string GenerateSecurityCode() { string securityCode = string.Empty; while (securityCode == string.Empty) { securityCode = PasswordGenerator.GeneratePassword(true, true, true, false, false, 12); securityCode = _context.ReferralCode.Where(s => s.SecutiryCode == securityCode).Any() ? string.Empty : securityCode; } return(securityCode); }
internal static Renewal Create(PasswordGenerator generator) { var ret = new Renewal { New = true, Id = ShortGuid.NewGuid().ToString(), PfxPassword = generator.Generate() }; return(ret); }
public void GeneratePassword_DefaultSettings_ReturnNewPassword() { // Arrange var passwordGenerator = new PasswordGenerator(); // Act var result = passwordGenerator.GeneratePassword(); // Assert result.Should().HaveLength(12); }
public void GeneratePassword() { // Arrange var passwordGenerator = new PasswordGenerator(); var characterCount = 10; CharacterVariant[] characterVariants = new[] { CharacterVariant.Lowercase, CharacterVariant.Special }; // Act and Assert passwordGenerator.GeneratePassword(characterCount, characterVariants); }
public void Generate_Should_ReturnPassword() { // Arrange var generator = new PasswordGenerator(123); // Act var password = generator.Generate(25); // Assert Assert.NotEqual(String.Empty, password.ToString()); }
public void GeneratePassword_NoVariantsSupplied_ThrowNullReferenceException() { // Arrange var passwordGenerator = new PasswordGenerator(); var characterCount = 10; CharacterVariant[] characterVariants = null !; // Act and Assert Assert.Throws <NullReferenceException>(() => passwordGenerator.GeneratePassword(characterCount, characterVariants)); }
public void GeneratePassword_NonPositiveCountSupplied_ThrowArgumentException() { // Arrange var passwordGenerator = new PasswordGenerator(); var characterCount = 0; CharacterVariant[] characterVariants = new[] { CharacterVariant.Lowercase, CharacterVariant.Special }; // Act and Assert Assert.Throws <ArgumentException>(() => passwordGenerator.GeneratePassword(characterCount, characterVariants)); }
public void Password_CanGeneratePassword() { // Arrange var generator = new PasswordGenerator(ThirtySeconds, ValidSecret); // Act var password = generator.Generate(ValidUid); // Assert Assert.NotEmpty(password); }
public void Password_CantValidatePasswordAgainstIncorrectUid() { // Arrange var generator = new PasswordGenerator(ThirtySeconds, ValidSecret); // Act var password = generator.Generate(ValidUid); var valid = generator.Validate(InvalidUid, password); // Assert Assert.False(valid); }
public void Password_CanValidateGeneratedPassword() { // Arrange var generator = new PasswordGenerator(ThirtySeconds, ValidSecret); // Act var password = generator.Generate(ValidUid); var valid = generator.Validate(ValidUid, password); // Assert Assert.True(valid); }
private static List <User> PrepareNewUsersToSend(UserRepository repo) { foreach (var user in repo.IncomeUserList) { PassAppResourcesConverter converter = new PassAppResourcesConverter(); user.Password = PasswordGenerator.Generate(converter.ResorcesStringToInt32Convert(Properties.Resources.MinPasswordLength), converter.ResorcesStringToInt32Convert(Properties.Resources.MaxPasswordLength)); user.Login = new LoginGenerator().LoginListGeneration(user); repo.UsersToSendlist.Add(user); } return(repo.UsersToSendlist); }
private void GenerateKey_Clik(object sender, RoutedEventArgs e) { PasswordGenerator PasswordGenerator = new PasswordGenerator(); PasswordGenerator.Minimum = 8; PasswordGenerator.Maximum = 12; // this.GeneratedkeytextBox1.AppendText(PasswordGenerator.Generate().ToString()); Guid OrganizationID = Guid.NewGuid(); this.GeneratedkeytextBox1.Clear(); this.GeneratedkeytextBox1.AppendText(OrganizationID.ToString()); }
public void Password_CantValidatePasswordAgainstIncorrectUid() { // Arrange var generator = new PasswordGenerator(ThirtySeconds, ValidSecret); // Act var password = generator.Generate(ValidUid); var valid = generator.Validate(InvalidUid, password); // Assert Assert.False(valid); }
public void Password_CanValidateGeneratedPassword() { // Arrange var generator = new PasswordGenerator(ThirtySeconds, ValidSecret); // Act var password = generator.Generate(ValidUid); var valid = generator.Validate(ValidUid, password); // Assert Assert.True(valid); }
public void AddPassword(IDomainIdentityService ids, PasswordGenerator pwds, string display, string login, string password) { if (_state.ContainsLogin(login)) throw DomainError.Named("duplicate-login", "Login {0} is already taken", login); var user = new UserId(ids.GetId()); var salt = pwds.CreateSalt(); var token = pwds.CreateToken(); var hash = pwds.HashPassword(password, salt); Apply(new SecurityPasswordAdded(_state.Id, user, display, login, hash, salt, token)); }
public void GeneratePasswordPhraseWithSpecialCharacterSeparatorInvalidSeparatorThrowsException() { // Arrange const string specialCharacter = "|"; // Act var testPasswordPhrase = PasswordGenerator.GeneratePasswordPhraseWithSpecialCharacterSeparator(specialCharacter); // Assert // Assert is Exception }
public void TestIfCorrectLengthIsCreated() { PasswordGenerator password = new PasswordGenerator(LENGTH_FIRST, LENGTH_FIRST, 2, 2, 3, 3); string pass = password.Generate(); Console.WriteLine("Password: "******"Password: " + pass); Assert.Equal(LENGTH_SECOND, pass.Length); }
public void GetPwdLengthTest() { // arrange int pwdLength = 8; PasswordGenerator pg = new PasswordGenerator(8, true, true, true, true); // act string result = pg.GetPwd(); // assert Assert.AreEqual(pwdLength, result.Length); }
internal static Renewal Create(string?id, int renewalDays, PasswordGenerator generator) { var ret = new Renewal { New = true, Id = string.IsNullOrEmpty(id) ? ShortGuid.NewGuid().ToString() : id, PfxPassword = new ProtectedString(generator.Generate()), RenewalDays = renewalDays }; return(ret); }
public PasswordGeneratorVM() : base("Password Generator") { _copyPassword = new Command(CopyToClipboard); //set default values for the password _passwordLength = 9; LengthText = "Your password length is " + _passwordLength; _includeSpecialChars = false; _includeUpperCaseLetters = false; _includeNumbers = false; //generate and display it Password = PasswordGenerator.GeneratePassword(_passwordLength, _includeUpperCaseLetters, _includeNumbers, _includeSpecialChars); }
public void GenerateXNumberOfPasswordPhrasesReturnsAListOfTheRightAmountOfRandomPasswordPhrasesValid() { // Arrange const int expected = 25; // Act var testPasswordPhrases = PasswordGenerator.GenerateXNumberOfStandardPasswordPhrases(25, SizeOfWords.Random); var actual = testPasswordPhrases.Count(); // Assert Assert.AreEqual(expected, actual); }
public void GeneratePasswordWithNegativeSpecialCausesArgumentOutOfRangeException() { // Arrange const int numberOfAlphabetical = 12; const int numberOfNumberical = 6; const int numberOfSpecialCharacters = -6; // Act var testPassword = PasswordGenerator.GeneratePassword(numberOfAlphabetical, numberOfNumberical, numberOfSpecialCharacters); // Assert is Exception }
public void TestGenerateLengthOnly() { PasswordGenerator generator = new PasswordGenerator(); string result = generator.GeneratePassword(new PasswordRequirements() { MaxLength = 16, MinLength = 8, }); Assert.IsTrue(result.Length >= 8 && result.Length <= 16); }
public void GeneratePassword_TenCharactersLong_ShouldBeTenCharacters() { // Arrange var passwordGenerator = new PasswordGenerator(); int characterCount = 10; // Act var result = passwordGenerator.GeneratePassword(characterCount); // Assert result.Should().HaveLength(characterCount); }
public void Test_password_strenght_matches() { Assert.Equal(0, PasswordGenerator.EstimatePasswordStrength("1111")); Assert.Equal(0, PasswordGenerator.EstimatePasswordStrength("2222222222")); Assert.Equal(4, PasswordGenerator.EstimatePasswordStrength("123456789")); Assert.Equal(73, PasswordGenerator.EstimatePasswordStrength("123456789A")); Assert.Equal(75, PasswordGenerator.EstimatePasswordStrength("123456789AB")); Assert.Equal(0, PasswordGenerator.EstimatePasswordStrength("CCCCCCCCC")); Assert.Equal(100, PasswordGenerator.EstimatePasswordStrength("8m6y2L2WhalkPDa")); Assert.Equal(68, PasswordGenerator.EstimatePasswordStrength("AA11bb00__")); Assert.Equal(89, PasswordGenerator.EstimatePasswordStrength("123456_789AB")); }
private static List <User> PrepareUsersToChangePassword(UserRepository repo) { repo.FailDeliveredList = repo.FailDeliveredList != null ? repo.FailDeliveredList : new List <User>(); foreach (var user in repo.IncomeUserList) { PassAppResourcesConverter converter = new PassAppResourcesConverter(); user.Password = PasswordGenerator.Generate(converter.ResorcesStringToInt32Convert(Properties.Resources.MinPasswordLength), converter.ResorcesStringToInt32Convert(Properties.Resources.MaxPasswordLength)); repo.UsersToSendlist.Add(user); } return(repo.UsersToSendlist); }
public void GeneratePassword_PasswordTooShortOrLong_ThrowsException() { Assert.Throws <Exception>(() => { PasswordGenerator.GeneratePassword(false, false, false, false, false, 3); }); Assert.Throws <Exception>(() => { PasswordGenerator.GeneratePassword(false, false, false, false, false, 1000); }); }
/// generate a new secure password public static string GetRandomSecurePassword() { double Entropy = 0; PasswordGenerator Generator = new PasswordGenerator(); // TODO An Entropy of 72 was deemed sufficient in 2014 but it should be raised in future years to accommodate the increase // in computing power and hence the lessening of time it would take to break a password of such an Entropy. while (Entropy < 72) { Generator.GeneratePassword(); Entropy = Generator.PasswordEntropy; } return Generator.Password; }
public void Password_CantValidateExpiredPassword() { // Arrange var timeProvider = new MockTimeProvider(); var generator = new PasswordGenerator(ThirtySeconds, ValidSecret, timeProvider); // Act var password = generator.Generate(ValidUid); timeProvider.Set(DateTime.UtcNow.AddSeconds(31)); var valid = generator.Validate(ValidUid, password); // Assert Assert.False(valid); }
public void When(IDomainIdentityService ids, PasswordGenerator pwds, CreateSecurityFromRegistration c) { Apply(new SecurityAggregateCreated(c.Id)); var user = new UserId(ids.GetId()); var salt = pwds.CreateSalt(); var token = pwds.CreateToken(); var hash = pwds.HashPassword(c.Pwd, salt); Apply(new SecurityPasswordAdded(c.Id, user, c.DisplayName, c.Login, hash, salt, token)); if (!string.IsNullOrEmpty(c.OptionalIdentity)) { AddIdentity(ids, pwds, c.DisplayName, c.OptionalIdentity); } Apply(new SecurityRegistrationProcessCompleted(c.Id, c.DisplayName, user, token, c.RegistrationId)); }
private void SetCurrentUserToOracleConnectionString(OracleConnectionString oracleConnectionString) { lock (this) { if (oracleConnectionString.HasProxyUserAndPassword) { oracleConnectionString.User = OracleUserId; oracleConnectionString.Password = null; } if (!oracleConnectionString.HasUser && !oracleConnectionString.HasProxyUserAndPassword) { oracleConnectionString.User = OracleUserId; var passwordGenerator = new PasswordGenerator(_identity); oracleConnectionString.Password = passwordGenerator.GeneratePassword(); } } }
protected void btnPwd_Click(object sender, EventArgs e) { PasswordGenerator pg = new PasswordGenerator(); pg.ExcludeSymbols = true; pg.Exclusions = "0oABCDEFGHIJKLMNOPQRSTUVWXYZ`~!@#$^*()-_=+[]{}\\|;:'\",./"; pg.Maximum = 10; pg.Minimum = 6; var list = Bmk.Find(Condition.Empty); foreach (var stu in list) { string xh = stu.xstbh.Trim(); MembershipUser user = Membership.GetUser(xh); if (user != null) { string oldPwd = user.ResetPassword(); stu.Password = pg.Generate(); stu.Save(); user.ChangePassword(oldPwd, stu.Password.Trim()); if (Roles.IsUserInRole(xh, "Students") == false) { Roles.AddUserToRole(xh, "Students"); } } else { stu.Password = pg.Generate(); stu.Save(); Membership.CreateUser(xh, stu.Password.Trim()); if (Roles.IsUserInRole(xh, "Students") == false) { Roles.AddUserToRole(xh,"Students"); } } } this.BindData(); }
static void Main(string[] args) { string passWord = "******"; String hash = MD5Calculator.GetHash(passWord); Console.WriteLine($"Hash voor '{passWord}' = {hash}"); var generator = new PasswordGenerator(8); Console.WriteLine($"\nAantal paswoorden van 8 hoofdletters: {generator.Count():N0}"); Console.WriteLine($"\nEerste 10 paswoorden van 8 hoofdletters:\n"); int count = 0; foreach (var password in generator) { Console.WriteLine($"{password}"); count++; if (count == 10) break; } Console.WriteLine("\n\nPress <enter> to end"); Console.ReadLine(); }
public ConcurrentQueue<string> Start(int passWordLength, int maxQueueLength) { running = true; queue = new ConcurrentQueue<string>(); pwdGen = new PasswordGenerator(passWordLength); Task job = new Task(() => { GeneratePasswords(maxQueueLength); }, cancelToken); job.Start(); return queue; }
public Salter() { PasswordGenerator = new PasswordGenerator(); Position = SaltPosition.Suffix; Length = DefaultSaltLength; }
protected void btnInput_Click(object sender, EventArgs e) { Button btn = (Button)sender; PasswordGenerator pg = new PasswordGenerator(); pg.ExcludeSymbols = true; pg.Maximum = 4; pg.Minimum = 2; for (int i = 0; i < this.GridView1.Rows.Count; i++) { BmkPwd bmkPwd = BmkPwd.FindById((long)this.GridView1.DataKeys[i].Value); CheckBox chkBase = (CheckBox)this.GridView1.Rows[i].FindControl("chkBase"); CheckBox chkBaseFoot = (CheckBox)this.GridView1.FooterRow.FindControl("chkBase"); if (chkBase.Checked || chkBaseFoot.Checked) { bmkPwd.Base = pg.Generate(); } CheckBox chkHome = (CheckBox)this.GridView1.Rows[i].FindControl("chkHome"); CheckBox chkHomeFoot = (CheckBox)this.GridView1.FooterRow.FindControl("chkHome"); if (chkHome.Checked || chkHomeFoot.Checked) { bmkPwd.Home = pg.Generate(); } CheckBox chkCzhj = (CheckBox)this.GridView1.Rows[i].FindControl("chkCzhj"); CheckBox chkCzhjFoot = (CheckBox)this.GridView1.FooterRow.FindControl("chkCzhj"); if (chkCzhj.Checked || chkCzhjFoot.Checked) { bmkPwd.Czhj = pg.Generate(); } CheckBox chkXqah = (CheckBox)this.GridView1.Rows[i].FindControl("chkXqah"); CheckBox chkXqahFoot = (CheckBox)this.GridView1.FooterRow.FindControl("chkXqah"); if (chkXqah.Checked || chkXqahFoot.Checked) { bmkPwd.Xqah = pg.Generate(); } CheckBox chkTcxm = (CheckBox)this.GridView1.Rows[i].FindControl("chkTcxm"); CheckBox chkTcxmFoot = (CheckBox)this.GridView1.FooterRow.FindControl("chkTcxm"); if (chkTcxm.Checked || chkTcxmFoot.Checked) { bmkPwd.Tcxm = pg.Generate(); } // CheckBox chkKm61 = (CheckBox)this.GridView1.Rows[i].FindControl("chkKm61"); CheckBox chkKm61Foot = (CheckBox)this.GridView1.FooterRow.FindControl("chkKm61"); if (chkKm61.Checked || chkKm61Foot.Checked) { bmkPwd.Km61 = pg.Generate(); } CheckBox chkKm62 = (CheckBox)this.GridView1.Rows[i].FindControl("chkKm62"); CheckBox chkKm62Foot = (CheckBox)this.GridView1.FooterRow.FindControl("chkKm62"); if (chkKm62.Checked || chkKm62Foot.Checked) { bmkPwd.Km62 = pg.Generate(); } CheckBox chkKm63 = (CheckBox)this.GridView1.Rows[i].FindControl("chkKm63"); CheckBox chkKm63Foot = (CheckBox)this.GridView1.FooterRow.FindControl("chkKm63"); if (chkKm63.Checked || chkKm63Foot.Checked) { bmkPwd.Km63 = pg.Generate(); } // // CheckBox chkKm71 = (CheckBox)this.GridView1.Rows[i].FindControl("chkKm71"); CheckBox chkKm71Foot = (CheckBox)this.GridView1.FooterRow.FindControl("chkKm71"); if (chkKm71.Checked || chkKm71Foot.Checked) { bmkPwd.Km71 = pg.Generate(); } CheckBox chkKm72 = (CheckBox)this.GridView1.Rows[i].FindControl("chkKm72"); CheckBox chkKm72Foot = (CheckBox)this.GridView1.FooterRow.FindControl("chkKm72"); if (chkKm72.Checked || chkKm72Foot.Checked) { bmkPwd.Km72 = pg.Generate(); } CheckBox chkKm73 = (CheckBox)this.GridView1.Rows[i].FindControl("chkKm73"); CheckBox chkKm73Foot = (CheckBox)this.GridView1.FooterRow.FindControl("chkKm73"); if (chkKm73.Checked || chkKm73Foot.Checked) { bmkPwd.Km73 = pg.Generate(); } CheckBox chkKm74 = (CheckBox)this.GridView1.Rows[i].FindControl("chkKm74"); CheckBox chkKm74Foot = (CheckBox)this.GridView1.FooterRow.FindControl("chkKm74"); if (chkKm74.Checked || chkKm74Foot.Checked) { bmkPwd.Km74 = pg.Generate(); } // CheckBox chkZhonghe = (CheckBox)this.GridView1.Rows[i].FindControl("chkZhonghe"); CheckBox chkZhongheFoot = (CheckBox)this.GridView1.FooterRow.FindControl("chkZhonghe"); if (chkZhonghe.Checked || chkZhongheFoot.Checked) { bmkPwd.Zhonghe = pg.Generate(); } CheckBox chkZy = (CheckBox)this.GridView1.Rows[i].FindControl("chkZy"); CheckBox chkZyFoot = (CheckBox)this.GridView1.FooterRow.FindControl("chkZy"); if (chkZy.Checked || chkZyFoot.Checked) { bmkPwd.Zy = pg.Generate(); } bmkPwd.Save(); } BindData(); }
public string Solution(string password) { var generator = new PasswordGenerator(); return generator.FindNextValidPassword(password); }
//Нажата кнопка записать private void btnSave_Click(object sender, EventArgs e) { cbLog.Items.Clear(); DataTable dt; string password=null; #region Check Data //Проверим все ли заполнено if (cbPosition.SelectedItem == null) { cbLog.Items.Add("Необходимо указать должность "); cbLog.SelectedIndex = cbLog.Items.Count - 1; return; } if (cbWorkPlace.SelectedItem == null) { cbLog.Items.Add("Необходимо местоположение"); cbLog.SelectedIndex = cbLog.Items.Count - 1; return; } if (cbDepartment.SelectedItem == null) { cbLog.Items.Add("Необходимо подразделение"); cbLog.SelectedIndex = cbLog.Items.Count - 1; return; } if (!CheckEmailNotExist(txbEmail.Text)) { cbLog.Items.Add("Необходимо указать корректный email"); cbLog.SelectedIndex = cbLog.Items.Count - 1; return; } #endregion #region Add User To Active Directory if (chbAddAD.Enabled && chbAddAD.Checked) { cbLog.Items.Add("Создаем пользователя AD"); cbLog.SelectedIndex = cbLog.Items.Count - 1; PasswordGenerator pass = new PasswordGenerator(); password = pass.GeneratePassword(5); //пароль для AD cbLog.Items.Add("Сгенерирован пароль: "+password); cbLog.SelectedIndex = cbLog.Items.Count - 1; UserPrincipal oUserPrincipal = m_ADcon.CreateNewUser("OU=RASU,DC=vniiaes-asutp,DC=lan", txbLogin.Text, password, txbName.Text, txbLastName.Text); oUserPrincipal.DisplayName = txbLastName.Text + " " + txbName.Text + " " + txbSecondName.Text; oUserPrincipal.MiddleName = txbSecondName.Text; //oUserPrincipal.PasswordNeverExpires = true; oUserPrincipal.EmailAddress = txbEmail.Text; //Добавляем пользователя в группы по умолчанию GroupPrincipal oGroupPrincipal = m_ADcon.GetGroup("OU=Share Permission,DC=vniiaes-asutp,DC=lan","grpPermLocalUsers"); if (oGroupPrincipal != null) { oGroupPrincipal.Members.Add(oUserPrincipal); oGroupPrincipal.Save(); } else { cbLog.Items.Add("Группа grpPermLocalUsers не найдена "); cbLog.SelectedIndex = cbLog.Items.Count - 1; } oGroupPrincipal = m_ADcon.GetGroup("OU=Bitrix, OU=Share Permission,DC=vniiaes-asutp,DC=lan", "1С-Битрикс - Сотрудники"); if (oGroupPrincipal != null) { oGroupPrincipal.Members.Add(oUserPrincipal); oGroupPrincipal.Save(); } else { cbLog.Items.Add("Группа Bitrix не найдена "); cbLog.SelectedIndex = cbLog.Items.Count - 1; } if (cbEnableWiFi.Checked) { oGroupPrincipal = m_ADcon.GetGroup("OU=Service Permission,DC=vniiaes-asutp,DC=lan", "Wi-Fi Users"); if (oGroupPrincipal != null) { oGroupPrincipal.Members.Add(oUserPrincipal); oGroupPrincipal.Save(); } else { cbLog.Items.Add("Группа Wi-Fi Users не найдена "); cbLog.SelectedIndex = cbLog.Items.Count - 1; } } oUserPrincipal.Save(); cbLog.Items.Add("Пользователь " + txbLogin.Text + " добавлен в AD"); cbLog.SelectedIndex = cbLog.Items.Count - 1; } #endregion #region Add User to Staff Table //Добавили пользователя string strFields="(Name,SecondName,LastName,Login,Birthday,WorkPlace,DepartmentID,PositionID,CreateTime,State,WorkRoom,LastChangeID)"; string strValues=string.Format(" values ('{0}','{1}','{2}','{3}',convert(datetime,'{4}',104 ),'{5}','{6}','{7}',GETDATE(),'0','{8}','{9}')", txbName.Text, txbSecondName.Text, txbLastName.Text, txbLogin.Text, dtpBirthday.Value.ToShortDateString(), (cbWorkPlace.SelectedItem as ListElement).Index, (cbDepartment.SelectedItem as ListElement).Index, (cbPosition.SelectedItem as ListElement).Index, txbRoom.Text, m_ChangerID.ToString() ); try { m_ITOSQLCommand.ExecuteSQLNotQuery("insert into staff " + strFields + strValues); } catch (SystemException ex) { cbLog.Items.Add("insert into staff " + strFields + strValues + " throw Exception"); cbLog.Items.Add(ex.Message); cbLog.SelectedIndex = cbLog.Items.Count - 1; return; } #endregion #region Add data to another tables //Считываем UserID втсавленной записи dt = m_ITOSQLCommand.ExecuteSQLCommand("select UserID from staff where login="******"'"+txbLogin.Text+"'"); if (dt.Rows.Count <= 0) { cbLog.Items.Add("Не найден UserId для Login " + txbLogin.Text); cbLog.SelectedIndex = cbLog.Items.Count - 1; return; } string strUserID = dt.Rows[0][0].ToString(); cbLog.Items.Add("Пользователь добавлен ID = "+strUserID); cbLog.SelectedIndex = cbLog.Items.Count - 1; DialogResult = DialogResult.OK; try { m_ITOSQLCommand.ExecuteSQLNotQuery(string.Format("insert into Emails (email, ChangeTime,State,ChangerID, UserID) values ('{0}',GETDATE(),'1','{1}','{2}')", txbEmail.Text, m_ChangerID.ToString(), strUserID)); dt = m_ITOSQLCommand.ExecuteSQLCommand("select EmailID from Emails where email = '" + txbEmail.Text + "'"); if (dt.Rows.Count <= 0) { cbLog.Items.Add("EmailID not find for " + txbEmail.Text); cbLog.SelectedIndex = cbLog.Items.Count - 1; return; } m_ITOSQLCommand.ExecuteSQLNotQuery("update staff set emailID='" + dt.Rows[0][0].ToString() + "' where UserID='" + strUserID + "'"); } catch (SystemException ex) { cbLog.Items.Add("Add email " + strFields + strValues + " throw Exception"); cbLog.Items.Add(ex.Message); cbLog.SelectedIndex = cbLog.Items.Count - 1; } cbLog.Items.Add("Email добавлен " + txbEmail.Text); cbLog.SelectedIndex = cbLog.Items.Count - 1; if (AskEmailfromStarlines(txbEmail.Text)) { cbLog.Items.Add("Отправлена заявка на созадние email " + txbEmail.Text); cbLog.SelectedIndex = cbLog.Items.Count - 1; } else { cbLog.Items.Add("Заявку на создание email отправить не удалось " + txbEmail.Text); cbLog.SelectedIndex = cbLog.Items.Count - 1; } //запись телефонов в базу for (int i = 0; i < lbPhone.Items.Count; i++) { try { m_ITOSQLCommand.ExecuteSQLNotQuery(string.Format("insert into Phones (PhoneNumber, Type, ChangerID, UserID, LastChanged) values ('{0}','{1}','{2}','{3}',GETDATE())", lbPhone.Items[i].ToString(), (lbPhoneType.Items[i] as ListElement).Index, m_ChangerID.ToString(), strUserID)); } catch (SystemException ex) { cbLog.Items.Add("Add Phone " +lbPhoneType.Items[i].ToString()+" "+lbPhone.Items[i].ToString()+ " throw Exception"); cbLog.Items.Add(ex.Message); cbLog.SelectedIndex = cbLog.Items.Count - 1; } cbLog.Items.Add("Телефон добавлен " + lbPhone.Items[i].ToString()); cbLog.SelectedIndex = cbLog.Items.Count - 1; } //запись пароля if (password!=null) { try { m_ITOSQLCommand.ExecuteSQLNotQuery(string.Format("insert into stfPasswords (Password, Type,LastChangerID,UserID) values ('{0}','{1}','{2}','{3}')", password, (int)ePasswordTypes.AD, m_ChangerID.ToString(), strUserID)); } catch (SystemException ex) { cbLog.Items.Add("Add Password " +password+ " throw Exception"); cbLog.Items.Add(ex.Message); cbLog.SelectedIndex = cbLog.Items.Count - 1; return; } cbLog.Items.Add("Пароль AD добавлен "); cbLog.SelectedIndex = cbLog.Items.Count - 1; } #endregion btnSave.Enabled = false; ///Close(); }
public void PasswordWithCustomLengthGenerator() { var length = 99; IGenerator<string> pwGen = new PasswordGenerator(length); var pw = (string) pwGen.Generate(); Assert.IsNotNull(pw); Assert.AreEqual(length, pw.Length); }
/// <summary> /// Starts the generator /// </summary> /// <param name="passWordLength"> password length </param> /// <param name="maxQueueLength"> max queue length </param> /// <returns></returns> public ConcurrentQueue<string> Start(int passWordLength, int maxQueueLength) { // pass args _passLength = passWordLength; _queueLength = maxQueueLength; // Args checks if (passWordLength < 1) throw new ArgumentException("Password length must be greater than 0."); if (maxQueueLength < 1) throw new ArgumentException("Queue length must be greater than 0."); // password generator _passGen = new PasswordGenerator(_passLength); // fill queue async _q = new ConcurrentQueue<string>(); var progress = new Progress<ulong>((count) => { if (ProgressChanged != null) ProgressChanged(count); }); var status = new Progress<ReportStatus>((stat) => { switch (stat) { case ReportStatus.STALLED: if (Stalled != null) Stalled(); break; case ReportStatus.FINISHED: if (GeneratorFinished != null) GeneratorFinished(); break; default: break; } }); Task.Run(() => { MaintainQueue(progress, status); }); return _q; }
/// <summary> /// Calculates the number of passwords /// </summary> /// <param name="characters"> number of characters </param> /// <returns> number of passwords </returns> public ulong NrOffPasswords(int characters) { PasswordGenerator p = new PasswordGenerator(characters); ulong n = p.Count(); return n; }
public void PasswordWithDefaultLengthGenerator() { IGenerator<string> pwGen = new PasswordGenerator(); var pw = (string) pwGen.Generate(); Assert.IsNotNull(pw); Assert.IsTrue(pw.Length == 10); }
private void btnADSave_Click(object sender, EventArgs e) { ADMethodsAccountManagement ADcon = new ADMethodsAccountManagement(); //проверяем, если такой пользователь уже есть if (ADcon.IsUserExisiting(tbLogin.Text)) { MessageBox.Show("Такой пользователь уже есть"); return; } string password= null; PasswordGenerator pass = new PasswordGenerator(); password = pass.GeneratePassword(5); //пароль для AD UserPrincipal oUserPrincipal = ADcon.CreateNewUser("OU=RASU,DC=vniiaes-asutp,DC=lan", tbLogin.Text, password, txbName.Text, txbLastName.Text); oUserPrincipal.DisplayName = txbLastName.Text + " " + txbName.Text + " " + txbSecondName.Text; oUserPrincipal.MiddleName = txbSecondName.Text; //oUserPrincipal.PasswordNeverExpires = true; oUserPrincipal.EmailAddress = lblMainEmail.Text; //Добавляем пользователя в группы по умолчанию GroupPrincipal oGroupPrincipal = ADcon.GetGroup("OU=Share Permission,DC=vniiaes-asutp,DC=lan", "grpPermLocalUsers"); if (oGroupPrincipal != null) { oGroupPrincipal.Members.Add(oUserPrincipal); oGroupPrincipal.Save(); } oGroupPrincipal = ADcon.GetGroup("OU=Bitrix, OU=Share Permission,DC=vniiaes-asutp,DC=lan", "1С-Битрикс - Сотрудники"); if (oGroupPrincipal != null) { oGroupPrincipal.Members.Add(oUserPrincipal); oGroupPrincipal.Save(); } oGroupPrincipal = ADcon.GetGroup("OU=Service Permission,DC=vniiaes-asutp,DC=lan", "Wi-Fi Users"); if (oGroupPrincipal != null) { oGroupPrincipal.Members.Add(oUserPrincipal); oGroupPrincipal.Save(); } oUserPrincipal.Save(); try { m_ITOSQLCommand.ExecuteSQLNotQuery(string.Format("update staff set Login='******' where UserID='{1}'", tbLogin.Text, m_SelectedUserIdx.ToString())); } catch (SystemException ex) { } if (password != null) { try { m_ITOSQLCommand.ExecuteSQLNotQuery(string.Format("insert into stfPasswords (Password, Type,LastChangerID,UserID) values ('{0}','{1}','{2}','{3}')", password, (int)ePasswordTypes.AD, m_ProgramUserIdx.ToString(), m_SelectedUserIdx.ToString())); } catch (SystemException ex) { } } }
private void button2_Click(object sender, EventArgs e) { ADMethodsAccountManagement ADcon = new ADMethodsAccountManagement(); PasswordGenerator pass = new PasswordGenerator(); for (int i = 0; i < checkedListBox1.SelectedItems.Count; i++) { DataTable dt = m_ITOSQLCommand.ExecuteSQLCommand("Select login, Name,SecondName,LastName,UserID, dbo.GetEmailByID(emailID) from staff where login='******'"); if (dt.Rows.Count > 0) { //создаем пользователя в AD string password = pass.GeneratePassword(5); ADcon.CreateNewUser("CN=Users,DC=vniiaes-asutp,DC=lan", dt.Rows[0][0].ToString(), password, dt.Rows[0][1].ToString(), dt.Rows[0][3].ToString()); string UserID = dt.Rows[0][4].ToString(); string login = dt.Rows[0][0].ToString(); UserPrincipal up = ADcon.GetUser(dt.Rows[0][0].ToString()); up.DisplayName = dt.Rows[0][3].ToString() + " " + dt.Rows[0][1].ToString() + " " + dt.Rows[0][2].ToString(); up.MiddleName = dt.Rows[0][2].ToString(); up.PasswordNeverExpires = true; up.EmailAddress = dt.Rows[0][5].ToString(); up.Save(); //TODO Переделать добавление в группы по умолчанию // ADcon.AddUserToGroup(dt.Rows[0][0].ToString(),"1С-Битрикс - Сотрудники") ADcon.AddUserToGroup(dt.Rows[0][0].ToString(), "grpPermLocalUsers"); //Сохраняем пароль if (m_ITOSQLCommand.ExecuteSQLNotQuery(string.Format("insert into stfPasswords (UserID,Type,Password,LastChangeID) values ('{0}','1','{1}','{2}')", UserID, password, m_ProgramUserIdx.ToString())) != 1) MessageBox.Show("Innsert Pass " + pass + " to User " + login + " fails"); } //checkedListBox1.SelectedItems[i] } }