Developer Documentation
C#
Updated September 19, 2026

Generate Secure Passwords in C#

Generate cryptographically secure random passwords without modulo bias in C#.

A password generator should draw randomness from the operating system or platform CSPRNG. Do not use predictable pseudo-random functions intended for simulations or UI effects.

Quick Start#

The following example uses the standard C# API or a widely used package for this task.

Quick start#

C#
1using System.Security.Cryptography;23const string alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%";4char[] chars = new char[];5for (int i = ; i < chars.Length; i++)6{7    chars[i] = alphabet[RandomNumberGenerator.GetInt32(alphabet.Length)];8}9string password = new(chars);10Console.WriteLine(password);

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Random numeric code#

C#
1int code = RandomNumberGenerator.GetInt32(, );2string pin = code.ToString("D6");3Console.WriteLine(pin);

Important Notes#

RandomNumberGenerator.GetInt32 avoids modulo bias for bounded values and is preferable to Random for security-sensitive secrets.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement Password in other languages: