NEWS

[C#] Hướng dẫn tạo mật khẩu ngẫu nhiên trong lập trình winform

[C#] Hướng dẫn tạo mật khẩu ngẫu nhiên trong lập trình winform
Đăng bởi: Thảo Meo - Lượt xem: 7295 10:57:05, 01/09/2020PHẦN MỀM

Xin chào các bạn, bài viết hôm nay mình sẻ tiếp tục hướng dẫn các bạn cách tạo mật khẩu ngẫu nhiên trong lập trình C#, Winform.

[C#] Generate password random winform

Trong nhiều ứng dụng web hay một số chương trình các bạn thường thấy lúc mới tạo tài khoản ứng dụng có phần nhập mật khẩu thường tạo mật khẩu random.

Trong một mật khẩu thường bao gồm các ký hiệu sau:

  1. Chữ thường (lower case)
  2. Chữ hoa (upper case)
  3. Số (numbers)
  4. Ký tự đặc biệt (specials) 
  5. Chiều dài của mật khẩu.

Thường một mật khẩu sẽ canh vào những yếu tố này để xác định mật khẩu đó có mạnh hay không (strong password).

Giao diện demo ứng dụng Random Password C#:

random_pass_csharp

Full source code c#:

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

namespace RandomPassword
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            var passwordRandom = GeneratePassword(chk_lowercase.Checked, chkUppercase.Checked, chkNumbers.Checked, chkSpecial.Checked, int.Parse(txtlength.Text));
           txt_password.Text = passwordRandom;
        }

        const string LOWER_CASE = "abcdefghijklmnopqursuvwxyz";
        const string UPPER_CASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        const string NUMBERS = "123456789";
        const string SPECIALS = @"!@£$%^&*()#€";


        public string GeneratePassword(bool useLowercase, bool useUppercase, bool useNumbers, bool useSpecial,
            int passwordSize)
        {
            char[] _password = new char[passwordSize];
            string charSet = ""; 
            System.Random _random = new Random();
            int counter;

           
            if (useLowercase) charSet += LOWER_CASE;

            if (useUppercase) charSet += UPPER_CASE;

            if (useNumbers) charSet += NUMBERS;

            if (useSpecial) charSet += SPECIALS;

            for (counter = 0; counter < passwordSize; counter++)
            {
                _password[counter] = charSet[_random.Next(charSet.Length - 1)];
            }

            return string.Join(null, _password);
        }


    }
}

Thanks for watching!

DOWNLOAD SOURCE

Tags: random password c#auto password c#

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn tạo mật khẩu ngẫu nhiên trong lập trình winform
Đăng bởi: Thảo Meo - Lượt xem: 7295 10:57:05, 01/09/2020PHẦN MỀM