A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Ported Password Generator to DevToys 2.0 (#1001)
Etienne BAUDOUXac5a289db384
diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csprojindex 7e2f4084b..56439c36c 100644--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj@@ -84,6 +84,11 @@<AutoGen>True</AutoGen><DependentUpon>HashAndChecksumGenerator.resx</DependentUpon></Compile>+ <Compile Update="Tools\Generators\Password\PasswordGenerator.Designer.cs">+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ <DependentUpon>PasswordGenerator.resx</DependentUpon>+ </Compile><Compile Update="Tools\Generators\UUID\UUIDGenerator.Designer.cs"><DesignTime>True</DesignTime><AutoGen>True</AutoGen>@@ -180,6 +185,10 @@<Generator>ResXFileCodeGenerator</Generator><LastGenOutput>HashAndChecksumGenerator.Designer.cs</LastGenOutput></EmbeddedResource>+ <EmbeddedResource Update="Tools\Generators\Password\PasswordGenerator.resx">+ <Generator>ResXFileCodeGenerator</Generator>+ <LastGenOutput>PasswordGenerator.Designer.cs</LastGenOutput>+ </EmbeddedResource><EmbeddedResource Update="Tools\Generators\UUID\UUIDGenerator.resx"><Generator>ResXFileCodeGenerator</Generator><LastGenOutput>UUIDGenerator.Designer.cs</LastGenOutput>diff --git a/src/app/dev/DevToys.Tools/Helpers/Core/CryptoRandom.cs b/src/app/dev/DevToys.Tools/Helpers/Core/CryptoRandom.csnew file mode 100644index 000000000..4e2fef8b8--- /dev/null+++ b/src/app/dev/DevToys.Tools/Helpers/Core/CryptoRandom.cs@@ -0,0 +1,131 @@+using System.Security.Cryptography;++namespace DevToys.Tools.Helpers.Core;++/// <summary>+/// A class that mimics the standard Random class in the .NET Framework - but uses a random number generator internally.+/// Taken from IdentityModel (ref.: https://github.com/IdentityModel/IdentityModel/ )+/// Taken from PasswordGenerator (ref.: https://github.com/Darkseal/PasswordGenerator/blob/master/CryptoRandom.cs )+/// </summary>+internal sealed class CryptoRandom : Random+{+ private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();+ private readonly byte[] _uint32Buffer = new byte[4];++ /// <summary>+ /// Output format for unique IDs+ /// </summary>+ private enum OutputFormat+ {+ /// <summary>+ /// URL-safe Base64+ /// </summary>+ Base64Url,+ /// <summary>+ /// Base64+ /// </summary>+ Base64,+ /// <summary>+ /// Hex+ /// </summary>+ Hex+ }++ /// <summary>+ /// Initializes a new instance of the <see cref="CryptoRandom"/> class.+ /// </summary>+ internal CryptoRandom()+ {+ }++ /// <summary>+ /// Returns a nonnegative random number.+ /// </summary>+ /// <returns>+ /// A 32-bit signed integer greater than or equal to zero and less than <see cref="F:System.Int32.MaxValue"/>.+ /// </returns>+ public override int Next()+ {+ Rng.GetBytes(_uint32Buffer);+ return BitConverter.ToInt32(_uint32Buffer, 0) & 0x7FFFFFFF;+ }++ /// <summary>+ /// Returns a nonnegative random number less than the specified maximum.+ /// </summary>+ /// <param name="maxValue">The exclusive upper bound of the random number to be generated. <paramref name="maxValue"/> must be greater than or equal to zero.</param>+ /// <returns>+ /// A 32-bit signed integer greater than or equal to zero, and less than <paramref name="maxValue"/>; that is, the range of return values ordinarily includes zero but not <paramref name="maxValue"/>. However, if <paramref name="maxValue"/> equals zero, <paramref name="maxValue"/> is returned.+ /// </returns>+ /// <exception cref="T:System.ArgumentOutOfRangeException">+ /// <paramref name="maxValue"/> is less than zero.+ /// </exception>+ public override int Next(int maxValue)+ {+ if (maxValue < 0)+ throw new ArgumentOutOfRangeException(nameof(maxValue));++ return Next(0, maxValue);+ }++ /// <summary>+ /// Returns a random number within a specified range.+ /// </summary>+ /// <param name="minValue">The inclusive lower bound of the random number returned.</param>+ /// <param name="maxValue">The exclusive upper bound of the random number returned. <paramref name="maxValue"/> must be greater than or equal to <paramref name="minValue"/>.</param>+ /// <returns>+ /// A 32-bit signed integer greater than or equal to <paramref name="minValue"/> and less than <paramref name="maxValue"/>; that is, the range of return values includes <paramref name="minValue"/> but not <paramref name="maxValue"/>. If <paramref name="minValue"/> equals <paramref name="maxValue"/>, <paramref name="minValue"/> is returned.+ /// </returns>+ /// <exception cref="T:System.ArgumentOutOfRangeException">+ /// <paramref name="minValue"/> is greater than <paramref name="maxValue"/>.+ /// </exception>+ public override int Next(int minValue, int maxValue)+ {+ if (minValue > maxValue)+ throw new ArgumentOutOfRangeException(nameof(minValue));++ if (minValue == maxValue)+ return minValue;++ long diff = maxValue - minValue;++ while (true)+ {+ Rng.GetBytes(_uint32Buffer);+ uint rand = BitConverter.ToUInt32(_uint32Buffer, 0);++ long max = 1 + (long)uint.MaxValue;+ long remainder = max % diff;+ if (rand < max - remainder)+ return (int)(minValue + rand % diff);+ }+ }++ /// <summary>+ /// Returns a random number between 0.0 and 1.0.+ /// </summary>+ /// <returns>+ /// A double-precision floating point number greater than or equal to 0.0, and less than 1.0.+ /// </returns>+ public override double NextDouble()+ {+ Rng.GetBytes(_uint32Buffer);+ uint rand = BitConverter.ToUInt32(_uint32Buffer, 0);+ return rand / (1.0 + uint.MaxValue);+ }++ /// <summary>+ /// Fills the elements of a specified array of bytes with random numbers.+ /// </summary>+ /// <param name="buffer">An array of bytes to contain random numbers.</param>+ /// <exception cref="T:System.ArgumentNullException">+ /// <paramref name="buffer"/> is null.+ /// </exception>+ public override void NextBytes(byte[] buffer)+ {+ if (buffer == null)+ throw new ArgumentNullException(nameof(buffer));++ Rng.GetBytes(buffer);+ }+}diff --git a/src/app/dev/DevToys.Tools/Helpers/PasswordGeneratorHelper.cs b/src/app/dev/DevToys.Tools/Helpers/PasswordGeneratorHelper.csnew file mode 100644index 000000000..b818946a2--- /dev/null+++ b/src/app/dev/DevToys.Tools/Helpers/PasswordGeneratorHelper.cs@@ -0,0 +1,107 @@+using System.Text;+using DevToys.Tools.Helpers.Core;++namespace DevToys.Tools.Helpers;++internal static class PasswordGeneratorHelper+{+ /// <summary>+ /// All non-alphanumeric characters.+ /// </summary>+ internal const string NonAlphanumeric = "!@#$%^&*";++ /// <summary>+ /// All lower case ASCII characters.+ /// </summary>+ internal const string LowercaseLetters = "abcdefghijkmnopqrstuvwxyz";++ /// <summary>+ /// All upper case ASCII characters.+ /// </summary>+ internal const string UppercaseLetters = "ABCDEFGHJKLMNOPQRSTUVWXYZ";++ /// <summary>+ /// All digits.+ /// </summary>+ internal const string Digits = "0123456789";++ internal static string GeneratePassword(+ int length,+ bool hasUppercase,+ bool hasLowercase,+ bool hasNumbers,+ bool hasSpecialCharacters,+ char[]? excludedCharacters)+ {+ if (length <= 0)+ {+ return string.Empty;+ }++ // Combine all character sets together.+ string[] randomChars = new[] {+ string.Empty,+ string.Empty,+ string.Empty,+ string.Empty+ };++ var rand = new CryptoRandom();+ var newPasswordCharacters = new List<char>();++ if (hasUppercase)+ {+ randomChars[0] = RemoveExcludedCharacters(UppercaseLetters, excludedCharacters);+ }++ if (hasLowercase)+ {+ randomChars[1] = RemoveExcludedCharacters(LowercaseLetters, excludedCharacters);+ }++ if (hasNumbers)+ {+ randomChars[2] = RemoveExcludedCharacters(Digits, excludedCharacters);+ }++ if (hasSpecialCharacters)+ {+ randomChars[3] = RemoveExcludedCharacters(NonAlphanumeric, excludedCharacters);+ }++ randomChars = randomChars.Where(r => r.Length > 0).ToArray();++ // Only continue if the user hasn't excluded everything.+ if (randomChars.Length != 0)+ {+ for (int j = 0; j < length; j++)+ {+ string rcs = randomChars[rand.Next(0, randomChars.Length)];+ newPasswordCharacters.Insert(rand.Next(0, newPasswordCharacters.Count), rcs[rand.Next(0, rcs.Length)]);+ }+ }++ return new string(newPasswordCharacters.ToArray());+ }++ private static string RemoveExcludedCharacters(string input, char[]? excludedCharacters)+ {+ if (excludedCharacters == null || excludedCharacters.Length == 0)+ {+ return input;+ }++ var excludedSet = new HashSet<char>(excludedCharacters); // HashSet provides a faster lookup than Array.Contains().+ var stringBuilder = new StringBuilder();++ foreach (char c in input)+ {+ if (!excludedSet.Contains(c))+ {+ stringBuilder.Append(c);+ }+ }++ return stringBuilder.ToString();+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Generators/Password/PasswordGenerator.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Generators/Password/PasswordGenerator.Designer.csnew file mode 100644index 000000000..515212b5d--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Generators/Password/PasswordGenerator.Designer.cs@@ -0,0 +1,369 @@+//------------------------------------------------------------------------------+// <auto-generated>+// This code was generated by a tool.+// Runtime Version:4.0.30319.42000+//+// Changes to this file may cause incorrect behavior and will be lost if+// the code is regenerated.+// </auto-generated>+//------------------------------------------------------------------------------++namespace DevToys.Tools.Tools.Generators.Password {+ using System;+++ /// <summary>+ /// A strongly-typed resource class, for looking up localized strings, etc.+ /// </summary>+ // This class was auto-generated by the StronglyTypedResourceBuilder+ // class via a tool like ResGen or Visual Studio.+ // To add or remove a member, edit your .ResX file then rerun ResGen+ // with the /str option, or rebuild your VS project.+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]+ internal class PasswordGenerator {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal PasswordGenerator() {+ }++ /// <summary>+ /// Returns the cached ResourceManager instance used by this class.+ /// </summary>+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]+ internal static global::System.Resources.ResourceManager ResourceManager {+ get {+ if (object.ReferenceEquals(resourceMan, null)) {+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Tools.Generators.Password.PasswordGenerator", typeof(PasswordGenerator).Assembly);+ resourceMan = temp;+ }+ return resourceMan;+ }+ }++ /// <summary>+ /// Overrides the current thread's CurrentUICulture property for all+ /// resource lookups using this strongly typed resource class.+ /// </summary>+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]+ internal static global::System.Globalization.CultureInfo Culture {+ get {+ return resourceCulture;+ }+ set {+ resourceCulture = value;+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Password Generator tool.+ /// </summary>+ internal static string AccessibleName {+ get {+ return ResourceManager.GetString("AccessibleName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Configuration.+ /// </summary>+ internal static string ConfigurationTitle {+ get {+ return ResourceManager.GetString("ConfigurationTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Generate random passwords.+ /// </summary>+ internal static string Description {+ get {+ return ResourceManager.GetString("Description", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Digit characters.+ /// </summary>+ internal static string Digits {+ get {+ return ResourceManager.GetString("Digits", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Use digit characters (0123456789).+ /// </summary>+ internal static string DigitsDescription {+ get {+ return ResourceManager.GetString("DigitsDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Digits.+ /// </summary>+ internal static string DigitsDescriptionStateOn {+ get {+ return ResourceManager.GetString("DigitsDescriptionStateOn", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Whether the generated password can include digits characters (0123456789).+ /// </summary>+ internal static string DigitsOptionDescription {+ get {+ return ResourceManager.GetString("DigitsOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to ExcludedCharacters.+ /// </summary>+ internal static string ExcludeCharacters {+ get {+ return ResourceManager.GetString("ExcludeCharacters", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Do not use the following characters to generate a password.+ /// </summary>+ internal static string ExcludeCharactersDescription {+ get {+ return ResourceManager.GetString("ExcludeCharactersDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Excluding '{0}'.+ /// </summary>+ internal static string ExcludedCharactersDescriptionState {+ get {+ return ResourceManager.GetString("ExcludedCharactersDescriptionState", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to A set of characters that should not be used to generate the password.+ /// </summary>+ internal static string ExcludedCharactersOptionDescription {+ get {+ return ResourceManager.GetString("ExcludedCharactersOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Generate Password(s).+ /// </summary>+ internal static string GenerateButton {+ get {+ return ResourceManager.GetString("GenerateButton", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Generate.+ /// </summary>+ internal static string GenerateTitle {+ get {+ return ResourceManager.GetString("GenerateTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Length.+ /// </summary>+ internal static string Length {+ get {+ return ResourceManager.GetString("Length", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to The length of the password to generate.+ /// </summary>+ internal static string LengthOptionDescription {+ get {+ return ResourceManager.GetString("LengthOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Password Generator.+ /// </summary>+ internal static string LongDisplayTitle {+ get {+ return ResourceManager.GetString("LongDisplayTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Lowercase characters.+ /// </summary>+ internal static string Lowercase {+ get {+ return ResourceManager.GetString("Lowercase", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Use lowercase characters (abcdefghijkmnopqrstuvwxyz).+ /// </summary>+ internal static string LowercaseDescription {+ get {+ return ResourceManager.GetString("LowercaseDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Lowercase.+ /// </summary>+ internal static string LowercaseDescriptionStateOn {+ get {+ return ResourceManager.GetString("LowercaseDescriptionStateOn", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Whether the generated password can include lowercase characters (abcdefghijkmnopqrstuvwxyz).+ /// </summary>+ internal static string LowercaseOptionDescription {+ get {+ return ResourceManager.GetString("LowercaseOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to x.+ /// </summary>+ internal static string MultiplySymbol {+ get {+ return ResourceManager.GetString("MultiplySymbol", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to No password(s) can be generated because no options have been selected..+ /// </summary>+ internal static string NoCharacterSetsWarning {+ get {+ return ResourceManager.GetString("NoCharacterSetsWarning", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Number of Passwords to generate.+ /// </summary>+ internal static string NumberOfPasswordsToGenerate_AutomationProperties_Name {+ get {+ return ResourceManager.GetString("NumberOfPasswordsToGenerate_AutomationProperties_Name", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Passwords.+ /// </summary>+ internal static string Output {+ get {+ return ResourceManager.GetString("Output", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Passkey Secret Pwd.+ /// </summary>+ internal static string SearchKeywords {+ get {+ return ResourceManager.GetString("SearchKeywords", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Password.+ /// </summary>+ internal static string ShortDisplayTitle {+ get {+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Special characters.+ /// </summary>+ internal static string SpecialCharacters {+ get {+ return ResourceManager.GetString("SpecialCharacters", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Use special characters (!@#$%^&*).+ /// </summary>+ internal static string SpecialCharactersDescription {+ get {+ return ResourceManager.GetString("SpecialCharactersDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Special characters.+ /// </summary>+ internal static string SpecialCharactersDescriptionStateOn {+ get {+ return ResourceManager.GetString("SpecialCharactersDescriptionStateOn", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Whether the generated password can include special characters (!@#$%^&*).+ /// </summary>+ internal static string SpecialCharactersOptionDescription {+ get {+ return ResourceManager.GetString("SpecialCharactersOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Uppercase characters.+ /// </summary>+ internal static string Uppercase {+ get {+ return ResourceManager.GetString("Uppercase", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Use uppercase characters (ABCDEFGHJKLMNOPQRSTUVWXYZ).+ /// </summary>+ internal static string UppercaseDescription {+ get {+ return ResourceManager.GetString("UppercaseDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Uppercase.+ /// </summary>+ internal static string UppercaseDescriptionStateOn {+ get {+ return ResourceManager.GetString("UppercaseDescriptionStateOn", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Whether the generated password can include uppercase characters (ABCDEFGHJKLMNOPQRSTUVWXYZ).+ /// </summary>+ internal static string UppercaseOptionDescription {+ get {+ return ResourceManager.GetString("UppercaseOptionDescription", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Generators/Password/PasswordGenerator.resx b/src/app/dev/DevToys.Tools/Tools/Generators/Password/PasswordGenerator.resxnew file mode 100644index 000000000..fe1b69877--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Generators/Password/PasswordGenerator.resx@@ -0,0 +1,222 @@+<?xml version="1.0" encoding="utf-8"?>+<root>+ <!--+ Microsoft ResX Schema++ Version 2.0++ The primary goals of this format is to allow a simple XML format+ that is mostly human readable. The generation and parsing of the+ various data types are done through the TypeConverter classes+ associated with the data types.++ Example:++ ... ado.net/XML headers & schema ...+ <resheader name="resmimetype">text/microsoft-resx</resheader>+ <resheader name="version">2.0</resheader>+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">+ <value>[base64 mime encoded serialized .NET Framework object]</value>+ </data>+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>+ <comment>This is a comment</comment>+ </data>++ There are any number of "resheader" rows that contain simple+ name/value pairs.++ Each data row contains a name, and value. The row also contains a+ type or mimetype. Type corresponds to a .NET class that support+ text/value conversion through the TypeConverter architecture.+ Classes that don't support this are serialized and stored with the+ mimetype set.++ The mimetype is used for serialized objects, and tells the+ ResXResourceReader how to depersist the object. This is currently not+ extensible. For a given mimetype the value must be set accordingly:++ Note - application/x-microsoft.net.object.binary.base64 is the format+ that the ResXResourceWriter will generate, however the reader can+ read any of the formats listed below.++ mimetype: application/x-microsoft.net.object.binary.base64+ value : The object must be serialized with+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter+ : and then encoded with base64 encoding.++ mimetype: application/x-microsoft.net.object.soap.base64+ value : The object must be serialized with+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter+ : and then encoded with base64 encoding.++ mimetype: application/x-microsoft.net.object.bytearray.base64+ value : The object must be serialized into a byte array+ : using a System.ComponentModel.TypeConverter+ : and then encoded with base64 encoding.+ -->+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />+ <xsd:element name="root" msdata:IsDataSet="true">+ <xsd:complexType>+ <xsd:choice maxOccurs="unbounded">+ <xsd:element name="metadata">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" />+ </xsd:sequence>+ <xsd:attribute name="name" use="required" type="xsd:string" />+ <xsd:attribute name="type" type="xsd:string" />+ <xsd:attribute name="mimetype" type="xsd:string" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="assembly">+ <xsd:complexType>+ <xsd:attribute name="alias" type="xsd:string" />+ <xsd:attribute name="name" type="xsd:string" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="data">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="resheader">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" />+ </xsd:complexType>+ </xsd:element>+ </xsd:choice>+ </xsd:complexType>+ </xsd:element>+ </xsd:schema>+ <resheader name="resmimetype">+ <value>text/microsoft-resx</value>+ </resheader>+ <resheader name="version">+ <value>2.0</value>+ </resheader>+ <resheader name="reader">+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <resheader name="writer">+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <data name="AccessibleName" xml:space="preserve">+ <value>Password Generator tool</value>+ </data>+ <data name="ConfigurationTitle" xml:space="preserve">+ <value>Configuration</value>+ </data>+ <data name="Description" xml:space="preserve">+ <value>Generate random passwords</value>+ </data>+ <data name="Digits" xml:space="preserve">+ <value>Digit characters</value>+ </data>+ <data name="DigitsDescription" xml:space="preserve">+ <value>Use digit characters (0123456789)</value>+ </data>+ <data name="DigitsDescriptionStateOn" xml:space="preserve">+ <value>Digits</value>+ </data>+ <data name="DigitsOptionDescription" xml:space="preserve">+ <value>Whether the generated password can include digits characters (0123456789)</value>+ </data>+ <data name="ExcludeCharacters" xml:space="preserve">+ <value>ExcludedCharacters</value>+ </data>+ <data name="ExcludeCharactersDescription" xml:space="preserve">+ <value>Do not use the following characters to generate a password</value>+ </data>+ <data name="ExcludedCharactersDescriptionState" xml:space="preserve">+ <value>Excluding '{0}'</value>+ </data>+ <data name="ExcludedCharactersOptionDescription" xml:space="preserve">+ <value>A set of characters that should not be used to generate the password</value>+ </data>+ <data name="GenerateButton" xml:space="preserve">+ <value>Generate Password(s)</value>+ </data>+ <data name="GenerateTitle" xml:space="preserve">+ <value>Generate</value>+ </data>+ <data name="Length" xml:space="preserve">+ <value>Length</value>+ </data>+ <data name="LengthOptionDescription" xml:space="preserve">+ <value>The length of the password to generate</value>+ </data>+ <data name="LongDisplayTitle" xml:space="preserve">+ <value>Password Generator</value>+ </data>+ <data name="Lowercase" xml:space="preserve">+ <value>Lowercase characters</value>+ </data>+ <data name="LowercaseDescription" xml:space="preserve">+ <value>Use lowercase characters (abcdefghijkmnopqrstuvwxyz)</value>+ </data>+ <data name="LowercaseDescriptionStateOn" xml:space="preserve">+ <value>Lowercase</value>+ </data>+ <data name="LowercaseOptionDescription" xml:space="preserve">+ <value>Whether the generated password can include lowercase characters (abcdefghijkmnopqrstuvwxyz)</value>+ </data>+ <data name="MultiplySymbol" xml:space="preserve">+ <value>x</value>+ </data>+ <data name="NoCharacterSetsWarning" xml:space="preserve">+ <value>No password(s) can be generated because no options have been selected.</value>+ </data>+ <data name="NumberOfPasswordsToGenerate_AutomationProperties_Name" xml:space="preserve">+ <value>Number of Passwords to generate</value>+ </data>+ <data name="Output" xml:space="preserve">+ <value>Passwords</value>+ </data>+ <data name="SearchKeywords" xml:space="preserve">+ <value>Passkey Secret Pwd</value>+ </data>+ <data name="ShortDisplayTitle" xml:space="preserve">+ <value>Password</value>+ </data>+ <data name="SpecialCharacters" xml:space="preserve">+ <value>Special characters</value>+ </data>+ <data name="SpecialCharactersDescription" xml:space="preserve">+ <value>Use special characters (!@#$%^&*)</value>+ </data>+ <data name="SpecialCharactersDescriptionStateOn" xml:space="preserve">+ <value>Special characters</value>+ </data>+ <data name="SpecialCharactersOptionDescription" xml:space="preserve">+ <value>Whether the generated password can include special characters (!@#$%^&*)</value>+ </data>+ <data name="Uppercase" xml:space="preserve">+ <value>Uppercase characters</value>+ </data>+ <data name="UppercaseDescription" xml:space="preserve">+ <value>Use uppercase characters (ABCDEFGHJKLMNOPQRSTUVWXYZ)</value>+ </data>+ <data name="UppercaseDescriptionStateOn" xml:space="preserve">+ <value>Uppercase</value>+ </data>+ <data name="UppercaseOptionDescription" xml:space="preserve">+ <value>Whether the generated password can include uppercase characters (ABCDEFGHJKLMNOPQRSTUVWXYZ)</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/Generators/Password/PasswordGeneratorCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Generators/Password/PasswordGeneratorCommandLineTool.csnew file mode 100644index 000000000..52ff352bb--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Generators/Password/PasswordGeneratorCommandLineTool.cs@@ -0,0 +1,65 @@+using DevToys.Tools.Helpers;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Tools.Generators.Password;++[Export(typeof(ICommandLineTool))]+[Name("PasswordGenerator")]+[CommandName(+ Name = "password",+ Alias = "pwd",+ ResourceManagerBaseName = "DevToys.Tools.Tools.Generators.Password.PasswordGenerator",+ DescriptionResourceName = nameof(PasswordGenerator.Description))]+internal sealed class PasswordGeneratorCommandLineTool : ICommandLineTool+{+ [CommandLineOption(+ Name = "length",+ Alias = "l",+ DescriptionResourceName = nameof(PasswordGenerator.LengthOptionDescription))]+ internal int Length { get; set; } = 30;++ [CommandLineOption(+ Name = "uppercase",+ Alias = "u",+ DescriptionResourceName = nameof(PasswordGenerator.UppercaseOptionDescription))]+ internal bool Uppercase { get; set; } = true;++ [CommandLineOption(+ Name = "lowercase",+ Alias = "m",+ DescriptionResourceName = nameof(PasswordGenerator.LowercaseOptionDescription))]+ internal bool Lowercase { get; set; } = true;++ [CommandLineOption(+ Name = "digits",+ Alias = "d",+ DescriptionResourceName = nameof(PasswordGenerator.DigitsOptionDescription))]+ internal bool Digits { get; set; } = true;++ [CommandLineOption(+ Name = "special",+ Alias = "s",+ DescriptionResourceName = nameof(PasswordGenerator.SpecialCharactersOptionDescription))]+ internal bool SpecialCharacters { get; set; } = true;++ [CommandLineOption(+ Name = "excluded",+ Alias = "e",+ DescriptionResourceName = nameof(PasswordGenerator.ExcludedCharactersOptionDescription))]+ internal string ExcludedCharacters { get; set; } = string.Empty;++ public ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)+ {+ string password+ = PasswordGeneratorHelper.GeneratePassword(+ Length,+ Uppercase,+ Lowercase,+ Digits,+ SpecialCharacters,+ ExcludedCharacters.ToArray());++ Console.WriteLine(password);+ return ValueTask.FromResult(0);+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Generators/Password/PasswordGeneratorGuidTool.cs b/src/app/dev/DevToys.Tools/Tools/Generators/Password/PasswordGeneratorGuidTool.csnew file mode 100644index 000000000..8e7929d24--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Generators/Password/PasswordGeneratorGuidTool.cs@@ -0,0 +1,313 @@+using System.Text;+using DevToys.Tools.Helpers;++namespace DevToys.Tools.Tools.Generators.Password;++[Export(typeof(IGuiTool))]+[Name("PasswordGenerator")]+[ToolDisplayInformation(+ IconFontName = "FluentSystemIcons",+ IconGlyph = '\uE8C9',+ GroupName = PredefinedCommonToolGroupNames.Generators,+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),+ ResourceManagerBaseName = "DevToys.Tools.Tools.Generators.Password.PasswordGenerator",+ ShortDisplayTitleResourceName = nameof(PasswordGenerator.ShortDisplayTitle),+ LongDisplayTitleResourceName = nameof(PasswordGenerator.LongDisplayTitle),+ DescriptionResourceName = nameof(PasswordGenerator.Description),+ AccessibleNameResourceName = nameof(PasswordGenerator.AccessibleName))]+internal sealed class PasswordGeneratorGuidTool : IGuiTool+{+ /// <summary>+ /// Whether the password should include uppercase characters.+ /// </summary>+ private static readonly SettingDefinition<bool> uppercase+ = new(+ name: $"{nameof(PasswordGeneratorGuidTool)}.{nameof(uppercase)}",+ defaultValue: true);++ /// <summary>+ /// Whether the password should include lowercase characters.+ /// </summary>+ private static readonly SettingDefinition<bool> lowercase+ = new(+ name: $"{nameof(PasswordGeneratorGuidTool)}.{nameof(lowercase)}",+ defaultValue: true);++ /// <summary>+ /// Whether the password should include numbers.+ /// </summary>+ private static readonly SettingDefinition<bool> numbers+ = new(+ name: $"{nameof(PasswordGeneratorGuidTool)}.{nameof(numbers)}",+ defaultValue: true);++ /// <summary>+ /// Whether the password should include special characters.+ /// </summary>+ private static readonly SettingDefinition<bool> specialCharacters+ = new(+ name: $"{nameof(PasswordGeneratorGuidTool)}.{nameof(specialCharacters)}",+ defaultValue: true);++ /// <summary>+ /// Excluded characters from password.+ /// </summary>+ private static readonly SettingDefinition<string> excludedCharacters+ = new(+ name: $"{nameof(PasswordGeneratorGuidTool)}.{nameof(excludedCharacters)}",+ defaultValue: string.Empty);++ /// <summary>+ /// How long the password should be.+ /// </summary>+ private static readonly SettingDefinition<int> length+ = new(+ name: $"{nameof(PasswordGeneratorGuidTool)}.{nameof(length)}",+ defaultValue: 30);++ /// <summary>+ /// How many passwords should be generated at once.+ /// </summary>+ private static readonly SettingDefinition<int> passwordsToGenerate+ = new(+ name: $"{nameof(PasswordGeneratorGuidTool)}.{nameof(passwordsToGenerate)}",+ defaultValue: 1);++ private enum GridColumn+ {+ Stretch+ }++ private enum GridRow+ {+ Settings,+ Results+ }++ private readonly ISettingsProvider _settingsProvider;+ private readonly IUIMultiLineTextInput _outputText = MultilineTextInput();+ private readonly IUISetting _excludedCharactersSetting = Setting();+ private readonly IUIInfoBar _infoBar = InfoBar();++ [ImportingConstructor]+ public PasswordGeneratorGuidTool(ISettingsProvider settingsProvider)+ {+ _settingsProvider = settingsProvider;++ OnGenerateButtonClick();+ }++ public UIToolView View+ => new(+ isScrollable: true,+ Grid()+ .ColumnLargeSpacing()+ .RowLargeSpacing()+ .Rows(+ (GridRow.Settings, Auto),+ (GridRow.Results, new UIGridLength(1, UIGridUnitType.Fraction)))+ .Columns(+ (GridColumn.Stretch, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Cells(+ Cell(+ GridRow.Settings,+ GridColumn.Stretch,+ Stack()+ .Vertical()+ .LargeSpacing()+ .WithChildren(++ Stack()+ .Vertical()+ .WithChildren(++ Label().Text(PasswordGenerator.ConfigurationTitle),++ SettingGroup()+ .Icon("FluentSystemIcons", '\uF57D')+ .Title(PasswordGenerator.Length)+ .InteractiveElement(+ NumberInput()+ .HideCommandBar()+ .Minimum(5)+ .OnValueChanged(OnLengthChanged)+ .Value(_settingsProvider.GetSetting(length)))+ .WithSettings(++ Setting()+ .Title(PasswordGenerator.Lowercase)+ .Description(PasswordGenerator.LowercaseDescription)+ .Handle(+ _settingsProvider,+ lowercase,+ stateDescriptionWhenOn: PasswordGenerator.LowercaseDescriptionStateOn,+ stateDescriptionWhenOff: null,+ OnSettingChanged),++ Setting()+ .Title(PasswordGenerator.Uppercase)+ .Description(PasswordGenerator.UppercaseDescription)+ .Handle(+ _settingsProvider,+ uppercase,+ stateDescriptionWhenOn: PasswordGenerator.UppercaseDescriptionStateOn,+ stateDescriptionWhenOff: null,+ OnSettingChanged),++ Setting()+ .Title(PasswordGenerator.Digits)+ .Description(PasswordGenerator.DigitsDescription)+ .Handle(+ _settingsProvider,+ numbers,+ stateDescriptionWhenOn: PasswordGenerator.DigitsDescriptionStateOn,+ stateDescriptionWhenOff: null,+ OnSettingChanged),++ Setting()+ .Title(PasswordGenerator.SpecialCharacters)+ .Description(PasswordGenerator.SpecialCharactersDescription)+ .Handle(+ _settingsProvider,+ specialCharacters,+ stateDescriptionWhenOn: PasswordGenerator.SpecialCharactersDescriptionStateOn,+ stateDescriptionWhenOff: null,+ OnSettingChanged),++ _excludedCharactersSetting+ .Title(PasswordGenerator.ExcludeCharacters)+ .StateDescription(GenerateExcludedCharactersDescriptionState())+ .InteractiveElement(+ SingleLineTextInput()+ .HideCommandBar()+ .Text(_settingsProvider.GetSetting(excludedCharacters))+ .OnTextChanged(OnExcludedCharactersChanged))),++ _infoBar+ .Warning()+ .Description(PasswordGenerator.NoCharacterSetsWarning)+ .NonClosable()),++ Stack()+ .Vertical()+ .WithChildren(++ Label().Text(PasswordGenerator.GenerateTitle),+ Stack()+ .Horizontal()+ .SmallSpacing()+ .WithChildren(++ Button()+ .AccentAppearance()+ .Text(PasswordGenerator.GenerateButton)+ .OnClick(OnGenerateButtonClick),++ Label().Style(UILabelStyle.BodyStrong).Text(PasswordGenerator.MultiplySymbol),++ NumberInput()+ .HideCommandBar()+ .Minimum(1)+ .Maximum(10000)+ .OnValueChanged(OnNumberOfPasswordsToGenerateChanged)+ .Value(_settingsProvider.GetSetting(passwordsToGenerate)))))),++ Cell(+ GridRow.Results,+ GridColumn.Stretch,++ _outputText+ .Title(PasswordGenerator.Output)+ .ReadOnly())));++ private bool HasAnyCharacterSets+ => _settingsProvider.GetSetting(uppercase)+ || _settingsProvider.GetSetting(lowercase)+ || _settingsProvider.GetSetting(numbers)+ || _settingsProvider.GetSetting(specialCharacters);++ public void OnDataReceived(string dataTypeName, object? parsedData)+ {+ }++ private void OnSettingChanged(bool value)+ {+ OnGenerateButtonClick();+ }++ private void OnLengthChanged(double value)+ {+ _settingsProvider.SetSetting(length, (int)value);+ OnGenerateButtonClick();+ }++ private void OnExcludedCharactersChanged(string value)+ {+ _settingsProvider.SetSetting(excludedCharacters, value);+ _excludedCharactersSetting.StateDescription(GenerateExcludedCharactersDescriptionState());++ OnGenerateButtonClick();+ }++ private void OnNumberOfPasswordsToGenerateChanged(double value)+ {+ _settingsProvider.SetSetting(passwordsToGenerate, (int)value);+ OnGenerateButtonClick();+ }++ private void OnGenerateButtonClick()+ {+ // There are no character sets selected, so we can't generate anything.+ if (!HasAnyCharacterSets)+ {+ _infoBar.Open();+ _outputText.Text(string.Empty);+ return;+ }+ else+ {+ _infoBar.Close();+ }++ bool hasUppercase = _settingsProvider.GetSetting(uppercase);+ bool hasLowercase = _settingsProvider.GetSetting(lowercase);+ bool hasNumbers = _settingsProvider.GetSetting(numbers);+ bool hasSpecialCharacters = _settingsProvider.GetSetting(specialCharacters);+ char[] excludedCharactersList = _settingsProvider.GetSetting(excludedCharacters).ToCharArray();+ int passwordLength = _settingsProvider.GetSetting(length);++ // Generate a random password using the the combined character set.+ var newPasswords = new StringBuilder();+ for (int i = 0; i < _settingsProvider.GetSetting(passwordsToGenerate); i++)+ {+ string password+ = PasswordGeneratorHelper.GeneratePassword(+ passwordLength,+ hasUppercase,+ hasLowercase,+ hasNumbers,+ hasSpecialCharacters,+ excludedCharactersList);++ if (password.Length > 0)+ {+ newPasswords.AppendLine(password);+ }+ }++ _outputText.Text(newPasswords.ToString());+ }++ private string GenerateExcludedCharactersDescriptionState()+ {+ if (_settingsProvider.GetSetting(excludedCharacters).Length == 0)+ {+ return string.Empty;+ }+ else+ {+ return string.Format(PasswordGenerator.ExcludedCharactersDescriptionState, _settingsProvider.GetSetting(excludedCharacters));+ }+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/PasswordGeneratorHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/PasswordGeneratorHelperTests.csnew file mode 100644index 000000000..2bf4ae6e1--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/PasswordGeneratorHelperTests.cs@@ -0,0 +1,80 @@+using DevToys.Tools.Helpers;++namespace DevToys.UnitTests.Tools.Helpers;++public class PasswordGeneratorHelperTests+{+ [Theory]+ [InlineData(1, true, false, false, false, null)]+ [InlineData(1, false, true, false, false, null)]+ [InlineData(1, false, false, true, false, null)]+ [InlineData(1, false, false, false, true, null)]+ [InlineData(100, true, true, true, true, null)]+ [InlineData(100, true, true, true, true, "bcdefghijklmnopqrstuvwxyz")]+ [InlineData(100, false, true, false, false, "bcdefghijklmnopqrstuvwxyz")]+ internal void GeneratePassword(int length, bool hasUppercase, bool hasLowercase, bool hasNumber, bool hasSpecialCharacters, string? excludedCharacters)+ {+ string password+ = PasswordGeneratorHelper.GeneratePassword(+ length,+ hasUppercase,+ hasLowercase,+ hasNumber,+ hasSpecialCharacters,+ excludedCharacters?.ToCharArray());++ password.Should().NotBeNullOrEmpty();+ password.Length.Should().Be(length);++ if (hasUppercase)+ {+ ContainAny(password, PasswordGeneratorHelper.UppercaseLetters);+ }+ else+ {+ NotContainAny(password, PasswordGeneratorHelper.UppercaseLetters);+ }++ if (hasLowercase)+ {+ ContainAny(password, PasswordGeneratorHelper.LowercaseLetters);+ }+ else+ {+ NotContainAny(password, PasswordGeneratorHelper.LowercaseLetters);+ }++ if (hasNumber)+ {+ ContainAny(password, PasswordGeneratorHelper.Digits);+ }+ else+ {+ NotContainAny(password, PasswordGeneratorHelper.Digits);+ }++ if (hasSpecialCharacters)+ {+ ContainAny(password, PasswordGeneratorHelper.NonAlphanumeric);+ }+ else+ {+ NotContainAny(password, PasswordGeneratorHelper.NonAlphanumeric);+ }++ if (excludedCharacters != null)+ {+ NotContainAny(password, excludedCharacters);+ }+ }++ private static void ContainAny(string password, string characters)+ {+ characters.Should().ContainAny(password.ToCharArray().Select(c => c.ToString()));+ }++ private static void NotContainAny(string password, string characters)+ {+ characters.Should().NotContainAny(password.ToCharArray().Select(c => c.ToString()));+ }+}