Генератор паролей си шарп

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

🔄 Simple password generator class library in C# 6.0, use for generate your own password! 📗

narekye/Password_Generator

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

C# 6.0 Visual Studio 2015 with .NET Framework 4.6 | SW version 1.0

Working with Password Generator class library.

You do not need to create a instance of Password class, because its imposible create instance of static class.

Use for generate many random passwords, which can improve you to secure somewhat.

How to add the Password class library in your project shown below.

Created class library with name PasswordGenerator (you must add the using PasswordGenerator; )which contains one static class which contains 1 staic field and 1 static method. Method has 1 parameter which is the length of password. In snippet shown the static class with his members.

using System; namespace PasswordGenerator  /// /// This class library used for generate random passwords. /// Used all digits, uppercase and downcase letters. /// Can send any parameter to 'Generate' method, which will generate password with sended count length. ///  public static class Password  private static string pass = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; public static string Generate(int length)  Random Rdpass = new Random(); string password = String.Empty; for (int i = 0; i  length; i++)  password += pass[Rdpass.Next(0, pass.Length)]; > return password; > > >

In the solution have added new project where testing class library. The testing was completed in Console application.

using System; using PasswordGenerator; // add this 'using' to use class library. namespace TestPasswordGenerator  class Program  static void Main()  //Parameter is lenght of your own password. Example 1. string mypassword = Password.Generate(4); Console.WriteLine(mypassword); // Or second one example below. Example 2 Console.WriteLine(Password.Generate(12)); // Delay !! Console.Read(); > > >

In this picture shown result of testing in console window.

Result

Whats new in second version | SW version 1.1

Added new non-static class named by HardPassword with new non-static method Generate .

You can create instance of HardPassword class using default constructor, because user constructors n class haven’t added.

There is a snippet of non-static class shown below.

public class HardPassword  private string pass = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@#$%^&*()-_=+|><>:;',./"; public string Generate(int length)  if (length>pass.Length)  throw new ArgumentOutOfRangeException("No much characters"); > Random rdpass = new Random(); string password = string.Empty; for (int i = 0; i  length; i++)  password += pass[rdpass.Next(rdpass.Next(i, pass.Length))]; > return password; > >

Updated too the test project shown by Console Application.

static void Main()  Console.WriteLine(); //Parameter is lenght of your own password. Example 1. string mypassword = Password.Generate(45); Console.WriteLine("\t First password with length 4 | ", mypassword); // Or second one example below. Example 2 Console.WriteLine("\t Second password with length 12 | ", Password.Generate(12)); var mypass = new HardPassword(); Console.WriteLine("\t Instance created by non-static class | " ,mypass.Generate(34)); // Delay !! Console.Read(); >

result

The result in Console window shown in picture.

Источник

Генератор паролей

Генератор паролей
Я ща фигню спрошу но все же. Есть генератор паролей, код ниже. Что то я не совсем так сделал.

Генератор паролей
Здравствуйте. Нужен был генератор паролей, но в интернете не нашел ничего подходящего. Немного.

Генератор паролей
Нужно написать программу-генератор паролей. Программа должна выполнять следующие действия: a) Ввод.

Генератор паролей
Программа должна выполнять следующие действия: a. Ввод идентификатора пользователя с клавиатуры.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
private readonly Liststring> Passwords = new Liststring> { "c8DzJeTC9t", "rvbrYASYyh", //. "" }; private readonly Random random = new Random(); private void button2_Click(object sender, EventArgs e) { var index = random.Next(Passwords.Count); var password = Passwords[index]; textBox1.Text = password; }

Добавлено через 3 минуты
Как с тобой связаться можно?

Вот посмотрите как я бы это делал.
Создается полностью автоматически случайный пароль (хотя читабельность у пароля уж очень плохая ), а не выбирается из заранее созданных пользователем в виде массива или списка.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
class Method { public string GetPass() { int [] arr = new int [16]; // сделаем длину пароля в 16 символов Random rnd = new Random(); string Password = ""; for (int i=0; iarr.Length; i++) { arr[i] = rnd.Next(33,125); Password += (char) arr[i]; } return Password; } } private void button2_Click(object sender, EventArgs e) { Method P = new Method(); var password = P.GetPass(); textBox1.Text = password; }

ЦитатаСообщение от buntar Посмотреть сообщение

Вот посмотрите как я бы это делал.
Создается полностью автоматически случайный пароль (хотя читабельность у пароля уж очень плохая ), а не выбирается из заранее созданных пользователем в виде массива или списка.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
class Method { public string GetPass() { int [] arr = new int [16]; // сделаем длину пароля в 16 символов Random rnd = new Random(); string Password = ""; for (int i=0; iarr.Length; i++) { arr[i] = rnd.Next(33,125); Password += (char) arr[i]; } return Password; } } private void button2_Click(object sender, EventArgs e) { Method P = new Method(); var password = P.GetPass(); textBox1.Text = password; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public static string GetPass(int x) { string pass=""; var r=new Random(); while (pass.Length  x) { Char c = (char)r.Next(33, 125); if (Char.IsLetterOrDigit(c)) pass += c; } return pass; } static void Main(string[] args) { string pass = GetPass(16); }

Tessen, ВО, класс! второй краше первого (с)!
Общими усилиями форумчан вообще получиться красота!

Можно еще и с перегрузочкой метода, чтобы не задавать кол-во символов пароля.

1 2 3 4 5 6 7 8 9 10 11 12
public static string GetPass() { string pass=""; var r=new Random(); while (pass.Length  16) { Char c = (char)r.Next(33, 125); if (Char.IsLetterOrDigit(c)) pass += c; } return pass; }

ЦитатаСообщение от buntar Посмотреть сообщение

1 2 3 4 5 6 7 8 9 10 11 12
public static string GetPass() { string pass=""; var r=new Random(); while (pass.Length  16) { Char c = (char)r.Next(33, 125); if (Char.IsLetterOrDigit(c)) pass += c; } return pass; }

а значения по умолчанию вам си шарпом зачем даны? чтобы перегрузочки писать?)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public static string GetPass(int x=16) { string pass = ""; var r = new Random(); while (pass.Length  x) { Char c = (char)r.Next(33, 125); if (Char.IsLetterOrDigit(c)) pass += c; } return pass; } static void Main(string[] args) { string pass = GetPass(); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
class Program { static readonly Random rndGen = new Random(); static void Main(string[] args) { const string rc = "qwertyuiopasdfghjklzxcvbnm0123456789"; for (int i = 5; i  50; i++) { Console.WriteLine(GetRandomPassword(rc, i)); } Console.ReadKey(); } /// /// Gets the random password. ///  /// Characters to generate password from. /// Length of the password. /// static string GetRandomPassword(string ch, int pwdLength) { char[] letters = ch.ToCharArray(); string s = ""; for (int i = 0; i  pwdLength; i++) { s+=letters[rndGen.Next(letters.Length)].ToString(); } return s; } }
string abc= "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!@#$%^&*()"; //набор символов int kol = 20; // кол-во символов string result = ""; random rnd = new random(); int lng = abc.length(); for(int i = 0; i  kol;i++) result += abc[rnd.Next(lng)];

Только учу с#, решил написать простой генератор паролей используя код приведенный выше. Посмотрите пжлст код, может у кого есть рекомендации по улучшению.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
private void button1_Click(object sender, EventArgs e) { string abc = "qwertyuiopasdfghjklzxcvbnm"; if (checkBox1.Checked == true)//использовать спецсимволы { abc += "!@#$%^&*()"; } if (checkBox2.Checked == true)//юзать цифры { abc += "123456789"; } if (checkBox3.Checked == true)//использовать заглавные { abc += "QWERTYUIOPASDFGHJKLZXCVBNM"; } int kol = (int)numericUpDown1.Value; // кол-во символов string result = ""; Random rnd = new Random(); int lng = abc.Length; for (int i = 0; i  kol; i++) result += abc[rnd.Next(lng)]; textBox1.Text = result; }
textBox1.Text = ""; string abc = "qwertyuiopasdfghjklzxcvbnm"; if (checkBox3.Checked)//использовать заглавные abc += abc.ToUpper(); if (checkBox1.Checked)//использовать спецсимволы abc += "!@#$%^&*()"; if (checkBox2.Checked)//юзать цифры abc += "123456789"; Random rnd = new Random(); for (int i = 0; i  numericUpDown1.Value; i++) textBox1.Text += abc[rnd.Next(abc.Length)];

ЦитатаСообщение от Tessen Посмотреть сообщение

textBox1.Text = ""; string abc = "qwertyuiopasdfghjklzxcvbnm"; if (checkBox3.Checked)//использовать заглавные abc += abc.ToUpper(); if (checkBox1.Checked)//использовать спецсимволы abc += "!@#$%^&*()"; if (checkBox2.Checked)//юзать цифры abc += "123456789"; Random rnd = new Random(); for (int i = 0; i  numericUpDown1.Value; i++) textBox1.Text += abc[rnd.Next(abc.Length)];
textBox1.Text += abc[rnd.Next([B]abc.Length[/B])];

Источник

Пишем простой генератор паролей на C#

Прочитав этот совет, вы сможете написать простой генератор паролей на С#.

Пишем простой генератор паролей на C#

Вот так это будет выглядеть:

Создаем новый проект WindowsFormsApplication и добавляем на форму: 2-а textBox, 4-и checkBox, один numericUpDown и одну кнопку (button). Размещаем компоненты на форме, так как вам нравиться, с соблюдением логики приложения.

Вопрос о оформлении компонентов не рассматриваться т.к. эта тема именно в данном контексте является очень простой и я считаю, что лучше уделить внимание коду.

Теперь пишем код в кнопке:

Первым делом необходимо сформировать словарь из которого будут генерироваться пароли, для этого пишем такой код: string dic = «»;
string tmp = «»;
if (checkBox1.Checked)
char nchar;
for (int i = 65; i

Думаю что принцип использования условий и циклов вопросов не вызовет, но при этом наверное следует пояснить смысл использования переменной nchar. В эту переменную мы будем писать значения из ASCII-таблицы.

string pass = «»;
Random mran = new Random();
for (int i = 0; i

Здесь можно разобрать подробно:

Объявляем переменную пароля: string pass = «»;

Объявляем переменную генератора случайных чисел: Random mran = new Random();

Цикл от 0 до numericUpDown1.Value, заданное на форме количество символов в пароле: for (int i = 0; i

Объявляем переменную и назначаем значение соответствующее случайному числу из промежутка от 0 до dic.Length, то есть длинны словаря: int index = Convert.ToUInt16(mran.NextDouble() * dic.Length) % dic.Length;

Объявляем переменную и назначаем значение соответствующего символу в словаре, стоящем под номером index: char ScharS = dic[index];

Добавляем сгенерированный символ к паролю: pass = Convert.ToString(ScharS);

Выводим значение переменной pass в текстовое поле на форме: textBox1.Text = pass;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
public partial class Form1 : Form
public Form1()
InitializeComponent();
>

private void button1_Click(object sender, EventArgs e)
string dic = «»;
string tmp = «»;
if (checkBox1.Checked)
char nchar;
for (int i = 65; i

Удачных проб, с уважением Сургай Владимир.

Источник

Читайте также:  Vuejs css in js
Оцените статью