How to generate random password in C#

3 Answers

0 votes
using System;
using System.Text;
 
public class Program
{
    public static string GenerateRandomPassword(int length) {
        string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%&";
 
        StringBuilder sb = new StringBuilder();
        Random rnd = new Random();
 
        for (int i = 0; i < length; i++) {
            int index = rnd.Next(chars.Length);
            sb.Append(chars[index]);
        }
 
        return sb.ToString();
    }
 
    public static void Main()
    {
        int length = 7;
 
        string password = GenerateRandomPassword(length);
        
        Console.WriteLine(password);
    }
}




 
/*
run:

cZ!v6tw

*/

 



answered Mar 28, 2023 by avibootz
0 votes
using System;
using System.Linq;
 
public class Program
{
    public static string GenerateRandomPassword(int length) {
        string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%&";
 
        Random rnd = new Random();
        
        return new string(Enumerable.Repeat(chars, length)
                .Select(s => s[rnd.Next(s.Length)]).ToArray());
    }
 
    public static void Main()
    {
        int length = 7;
 
        string password = GenerateRandomPassword(length);
        
        Console.WriteLine(password);
    }
}




 
/*
run:

@%un917

*/

 



answered Mar 28, 2023 by avibootz
0 votes
using System;
using System.Security.Cryptography;
 
public class Program
{
    public static string GenerateRandomPassword(int length) {
        byte[] password = new byte[length];
        
        RNGCryptoServiceProvider rngCrypt = new RNGCryptoServiceProvider();
        rngCrypt.GetBytes(password);
        
        return Convert.ToBase64String(password);
    }
 
    public static void Main()
    {
        int length = 7;
 
        string password = GenerateRandomPassword(length);
        
        Console.WriteLine(password);
    }
}




 
/*
run:

ohB8E73Vog==

*/

 



answered Mar 28, 2023 by avibootz

Related questions

1 answer 131 views
1 answer 107 views
1 answer 108 views
1 answer 95 views
1 answer 100 views
100 views asked Dec 22, 2024 by avibootz
3 answers 165 views
165 views asked Dec 22, 2024 by avibootz
2 answers 128 views
128 views asked Dec 21, 2024 by avibootz
...