Password generator: Difference between revisions

added RPL
(added RPL)
 
(34 intermediate revisions by 20 users not shown)
Line 33:
<!-- or zed, on the other side of the pond. -->
<br><br>
 
=={{header|6502 Assembly}}==
Unfortunately, easy6502 cannot display text, but it does have a random number generator, so this example merely contains the logic for generating the password itself. The screen can only display colored pixels, and the top 4 bytes are masked off, so this is just a visual aid to show the process in action. The X register is loaded with the password's length (in this case, 20 characters, not counting the null terminator.)
<syntaxhighlight lang="6502asm">LDY #0
LDX #20
LOOP:
LDA $FE ;load a random byte
BMI LOOP ;IF GREATER THAN 7F, ROLL AGAIN
CMP #$21 ;ASCII CODE FOR !
BCC LOOP
CMP #$5C
BEQ LOOP ;NO \
CMP #$60
BEQ LOOP ;NO `
;else, must be a good character
STA $0200,Y
INY
DEX
BNE LOOP
BRK ;end program</syntaxhighlight>
 
{{out}}
Code was executed three times and generated the following passwords:
<pre>vPX[d5gUY_5lUj[bNDS1
hY+%]lM*j~1Z4YG!0X0<
v}N|4dK(b71qgi-gGwkq</pre>
 
=={{header|8086 Assembly}}==
 
This program runs under MS-DOS. The number and length of passwords are given as command line arguments,
and there are command line options <code>/E</code> (to exclude <code>Il1 O0 5S 2Z</code> from the
passwords), and <code>/S</code> (to set the seed for the RNG, without this option the system time is used).
Help is printed when no arguments are given.
 
<syntaxhighlight lang="asm"> cpu 8086
bits 16
;;; MS-DOS syscalls
gettim: equ 2Ch ; Get system time
write: equ 40h ; Write to file
exit: equ 4Ch ; Exit with return code
;;; MS-DOS process data
arg: equ 80h ; Command line argument (length + string)
;;; BIOS calls
conout: equ 0Eh ; Write character to console
vstate: equ 0Fh ; Get current video state
section .text
org 100h
mov ah,gettim ; Seed the RNG using the system time
int 21h ; (in case of no argument)
mov [rnddat],cx
mov [rnddat+2],dx
mov si,arg ; See if we have any arguments
lodsb
test al,al
jnz hasarg
jmp usage ; If not, print usage string
;;; Parse the command line arguments
hasarg: xor bx,bx ; We do, zero-terminate the string
xchg al,bl
mov [si+bx],al
mov di,count ; Place to start reading arguments
doarg: lodsb ; Get argument byte
.chr: test al,al ; Zero?
jnz .arg ; If not, there are arguments left
jmp check ; If so, we're done
.arg: cmp al,' ' ; Space?
je doarg ; Then get next character
cmp al,'/' ; Option?
je opt
dec byte [nargs] ; Otherwise, it's an argument
jnz rdnum ; Read a number if we still need one
jmp usage ; Otherwise, incorrect arguments
rdnum: xor bp,bp ; Place to keep number
.chr: mov bl,al ; Keep the character in case not a digit
sub al,'0' ; Make into digit
cmp al,9 ; Valid digit?
ja .done ; If not, done with number
add bp,bp ; Multiply accumulator by 10
mov dx,bp
add bp,bp
add bp,bp
add bp,dx
xor ah,ah ; Then add the digit
add bp,ax
lodsb ; Read next digit
jmp .chr
.done: mov ax,bp ; Write the number into memory
stosw
mov al,bl ; Restore the character (next argument)
jmp doarg.chr
opt: lodsb ; Get option character
or al,32 ; Make lowercase
cmp al,'e' ; E?
je .e
cmp al,'s' ; S?
je .s
jmp usage ; If not, invalid argument
.e: inc byte [excl] ; /E: turn on exclusion
jmp doarg
.s: lodsb ; /S: should be followed by '='
cmp al,'='
je .s_ok
jmp usage ; If not, invalid argument
.s_ok: xor bp,bp ; DX:BP = RNG state
xor dx,dx
.hex: lodsb ; Get (potential) hex digit
mov ah,al ; Keep it around
call hexdgt ; Parse hexadecimal digit
jnc .hdone ; If invalid, we're done
shl bp,1 ; Make room for it in the state
rcl dx,1 ; Because it's a 32-bit value,
shl bp,1 ; which is stored in two 16-bit registers,
rcl dx,1 ; we have to shift and rotate the bits
shl bp,1 ; one by one.
rcl dx,1
shl bp,1
rcl dx,1
or dl,al ; Finally, add in the hexadecimal digit
jmp .hex
.hdone: mov [rnddat],bp ; Store random seed
mov [rnddat+2],dx
mov al,ah ; Restore the next character
jmp doarg.chr
;;; Check the arguments
check: dec byte [nargs] ; Were all arguments used?
jz .argok
jmp usage
.argok: mov cx,[count] ; CX = count
mov bp,[length] ; BP = length
test cx,cx ; Sanity check (count must not be zero)
mov si,errmsg.cnt
jnz .cntok
jmp error
.cntok: cmp bp,4 ; Length must be at least four
mov si,errmsg.len
jae .len2
jmp error
.len2: cmp bp,255 ; Length must be no more than 255
mov si,errmsg.lmax
jbe mkmask
jmp error
;;; Make a bitmask in which BP fits (for generating random
;;; numbers in the right range)
mkmask: mov cx,bp
mov bx,cx
.loop: shr cx,1
or bx,cx
test cx,cx
jnz .loop
stc
rcl bx,1
mov [lmask],bl ; Password <= 255 chars
;;; Generate a password
genpwd: lea cx,[bp-4] ; Get length minus four
mov di,buffer ; Write password into buffer
mov dl,[excl] ; Exclusion flag
mov bx,lc ; A lowercase letter,
mov ah,lc.len
call rndchr
mov bx,uc ; An uppercase letter
call rndchr ; (same length of course)
mov bx,dgt ; A digit,
mov ah,dgt.len
call rndchr
mov bx,sym ; And a symbol
mov ah,sym.len
call rndchr
test cx,cx ; If CX=0, we need no extra characters
jz .done
mov bx,cr ; Otherwise, we need CX extra characters
mov ah,cr.len
.loop: call rndchr
loop .loop
.done: mov ax,0A0Dh ; End with a newline
stosw
;;; Swap the first four characters with random characters
;;; from the password, so the four necessary characters won't
;;; necessarily be at the beginning.
swap: mov dx,bp ; Get length
mov dh,[lmask] ; Load the mask
mov si,buffer ; Password buffer
xor bh,bh
xor ah,ah ; Starting at zero
.loc: call rand ; Get random byte
and al,dh ; Mask off unused bits
cmp al,dl ; Result within password?
jae .loc ; If not, get another random number
mov bl,ah ; Load first character in CL
mov cl,[si+bx]
mov bl,al ; Load random character in CH
mov ch,[si+bx]
mov [si+bx],cl ; Write them back the other way around
mov bl,ah
mov [si+bx],ch
inc ah ; Next character
cmp ah,4 ; Are we there yet?
jb .loc ; If not, do another character.
;;; Write password to standard output
xor bx,bx ; File handle 0 = stdout
lea cx,[bp+2] ; Length = password length + 2 (for newline)
mov dx,si ; Location of password
mov ah,write ; Write the password
int 21h
jnc .ok ; Carry clear = success
mov si,errmsg.wrt ; Otherwise, print error message
jmp error
.ok: dec word [count] ; Need any more passwords?
jz stop ; If not, stop
jmp genpwd ; Otherwise, make another password
;;; Quit with return code 0 (success)
stop: mov ax,exit<<8
int 21h
;;; Generate a random character. BX=table, AH=length,
;;; DL=exclusion on/off
rndchr: call rand ; Random number
and al,7Fh ; from 0 to 127
cmp al,ah ; Within valid length?
jae rndchr ; If not, get new random number
xlatb ; Otherwise, get character from table
test dl,dl ; Is exclusion on?
jz .out ; If not, just store it
push cx ; Otherwise, keep CX around,
push di ; and DI,
mov cx,ex.len ; See if character is in exclusion table
mov di,ex
repne scasb
pop di ; restore DI
pop cx ; Restore CX
je rndchr ; And if it was found, get another character
.out: stosb ; Store in password buffer
ret
;;; Random number generator using XABC algorithm
;;; Returns random byte in AL
rand: push cx
push dx
mov cx,[rnddat] ; CH=X CL=A
mov dx,[rnddat+2] ; DH=B DL=C
inc ch ; X++
xor cl,ch ; A ^= X
xor cl,dl ; A ^= C
add dh,cl ; B += A
mov al,dh ; C' = B
shr al,1 ; C' >>= 1
xor al,cl ; C' ^= A
add al,dl ; C' += C
mov dl,al ; C = C'
mov [rnddat],cx
mov [rnddat+2],dx
pop dx
pop cx
ret
;;; If AL is a hexadecimal digit in ASCII, set AL to be its
;;; value. Carry flag set if digit was valid.
hexdgt: or al,32 ; Make letter lowercase (numbers unchanged)
sub al,'0' ; Subtract 0
cmp al,10 ; If it is a valid digit now, we're done
jc .out
sub al,39 ; Otherwise, correct for
cmp al,17
.out: ret
;;; Write the help message, and stop with return code 2
usage: mov si,help
;;; Write an error message, directly to the console, bypassing
;;; DOS to ensure it does not end up in the redirected output.
;;; Then, stop with return code 2 (failure)
error: mov ah,vstate ; Retrieve current video state
int 10h ; (this sets BH = current page)
.loop lodsb ; Get string byte
test al,al ; Zero?
jz .out ; Then we have reached the end
mov ah,conout ; Otherwise, write the character
int 10h
jmp .loop ; And get another one
.out: mov ax,exit<<8|2 ; Stop with error code 2
int 21h
section .data
nargs: db 3 ; We need two non-option arguments
excl: db 0 ; Exclusion is off by default
cr: ;;; Password characters
lc: db 'abcdefghijklmnopqrstuvwxyz'
.len: equ $-lc
uc: db 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.len: equ $-uc
dgt: db '0123456789'
.len: equ $-dgt
sym: db '!"#$%&()*+,-./:;<=>?@[]^_{|}~',39 ; 39=single quote
.len: equ $-sym
cr.len: equ $-cr
ex: db 'Il1O05S2Z' ; Excluded characters
.len: equ $-ex
;;; Help message
help: db 'PASSGEN [/S=seed] [/E] count length',13,10
db 9,'generate <count> passwords of length <length>',13,10
db 13,10
db 9,'/S=seed: set RNG seed (hexadecimal number)',13,10
db 9,'/E: exclude visually similar characters',13,10
db 0
errmsg: ;;; Error messages
.len: db 'Minimum password length is 4.',0
.lmax: db 'Maximum password length is 255.',0
.cnt: db 'At least one password must be generated.',0
.wrt: db 'Write error.',0
section .bss
count: resw 1 ; Amount of passwords to generate
length: resw 1 ; Length of passwords
lmask: resb 1 ; Mask for random number generation
rnddat: resb 4 ; RNG state
buffer: resb 257 ; Space to store password</syntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE FUNC GetNumParam(CHAR ARRAY text BYTE min,max)
BYTE res
 
DO
PrintF("Input %S (%B-%B): ",text,min,max)
res=InputB()
UNTIL res>=min AND res<=max
OD
RETURN (res)
 
BYTE FUNC GetBoolParam(CHAR ARRAY text)
CHAR ARRAY s(255)
 
DO
PrintF("%S? (Y/N): ",text)
InputS(s)
IF s(0)=1 THEN
IF s(1)='y OR s(1)='Y THEN
RETURN (1)
ELSEIF s(1)='n OR s(1)='N THEN
RETURN (0)
FI
FI
OD
RETURN (0)
 
PROC Shuffle(CHAR ARRAY s)
BYTE i,j
CHAR tmp
 
i=s(0)
WHILE i>1
DO
j=Rand(i)+1
tmp=s(i) s(i)=s(j) s(j)=tmp
i==-1
OD
RETURN
 
BYTE FUNC Contains(CHAR ARRAY s CHAR c)
BYTE i
 
IF s(0)=0 THEN
RETURN (0)
FI
FOR i=1 TO s(0)
DO
IF s(i)=c THEN
RETURN (1)
FI
OD
RETURN (0)
 
CHAR FUNC RandChar(CHAR ARRAY s,unsafe)
BYTE len
CHAR c
 
len=s(0)
DO
c=s(Rand(len)+1)
UNTIL Contains(unsafe,c)=0
OD
RETURN (c)
 
PROC Generate(CHAR ARRAY res BYTE len,safe)
DEFINE PTR="CARD"
CHAR ARRAY st,
upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ",
lower="abcdefghijklmnopqrstuvwxyz",
numbers="0123456789",
special="!""#$%&'()*+,-./:;<=>?@[]^_|",
unsafe="Il1O05S2Z"
PTR ARRAY sets(4)
BYTE i
 
sets(0)=upper sets(1)=lower
sets(2)=numbers sets(3)=special
 
res(0)=len
FOR i=1 TO len
DO
IF safe THEN
res(i)=RandChar(sets(i MOD 4),unsafe)
ELSE
res(i)=RandChar(sets(i MOD 4),"")
FI
OD
Shuffle(res)
RETURN
 
PROC PrintHelp()
PutE()
PrintE("Program generates random passwords")
PrintE("containing at least one upper-case")
PrintE("letter, one lower-case letter, one")
PrintE("digit and one special character.")
PrintE("It is possible to exclude visually")
PrintE("similar characters Il1O05S2Z.")
PutE()
RETURN
 
PROC Main()
BYTE len,count,safe,i,again,help
CHAR ARRAY password(255)
 
help=GetBoolParam("Show help")
IF help THEN
PrintHelp()
FI
 
DO
len=GetNumParam("length of password",4,30)
safe=GetBoolParam("Exclude similar chars")
count=GetNumParam("number of passwords",1,10)
PutE()
FOR i=1 TO count
DO
Generate(password,len,safe)
PrintF("%B. %S%E",i,password)
OD
PutE()
again=GetBoolParam("Generate again")
UNTIL again=0
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Password_generator.png Screenshot from Atari 8-bit computer]
<pre>
Show help? (Y/N): Y
 
Program generates random passwords
containing at least one upper-case
letter, one lower-case letter, one
digit and one special character.
It is possible to exclude visually
similar characters Il1O05S2Z.
 
Input length of password (4-30): 25
Exclude similar chars? (Y/N): Y
Input number of passwords (1-10): 6
 
1. 'Eo4qRf3379LF;-D&|s8bdaC+
2. L'3nw+N94J9tw*Bx=vR9+6L.p
3. @7uAAjj3"Vi@r$E767'iE;Fm3
4. 3y)^4Lb9f8^oVT_]nVK33n>Nr
5. vi4>Xv46G(eK<P6dCq;#zU6-9
6. ^-/MwtrpvzW7;K36Y7jJ_8X8*
 
Generate again? (Y/N): N
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Numerics.Discrete_Random;
with Ada.Strings.Fixed;
with Ada.Command_Line;
with Ada.Integer_Text_IO;
with Ada.Text_IO;
 
procedure Mkpw is
 
procedure Put_Usage;
procedure Parse_Command_Line (Success : out Boolean);
function Create_Password (Length : in Positive;
Safe : in Boolean)
return String;
 
procedure Put_Usage is
use Ada.Text_IO;
begin
Put_Line ("Usage: ");
Put_Line (" mkpw help - Show this help text ");
Put_Line (" mkpw [count <n>] [length <l>] [seed <s>] [safe] ");
Put_Line (" count <n> - Number of passwords generated (default 4)");
Put_Line (" length <l> - Password length (min 4) (default 4)");
Put_Line (" seed <l> - Seed for random generator (default 0)");
Put_Line (" safe - Do not use unsafe characters (0O1lIS52Z)");
end Put_Usage;
 
Lower_Set : constant String := "abcdefghijklmnopqrstuvwxyz";
Upper_Set : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Digit_Set : constant String := "0123456789";
Spec_Set : constant String := "!""#$%&'()*+,-./:;<=>?@[]^_{|}~";
Unsafe_Set : constant String := "0O1lI5S2Z";
 
Full_Set : constant String := Lower_Set & Upper_Set & Digit_Set & Spec_Set;
subtype Full_Indices is Positive range Full_Set'Range;
 
package Full_Index_Generator is
new Ada.Numerics.Discrete_Random (Full_Indices);
 
Index_Generator : Full_Index_Generator.Generator;
 
Config_Safe : Boolean := False;
Config_Count : Natural := 4;
Config_Length : Positive := 6;
Config_Seed : Integer := 0;
Config_Show_Help : Boolean := False;
 
procedure Parse_Command_Line (Success : out Boolean) is
use Ada.Command_Line;
Got_Safe, Got_Count : Boolean := False;
Got_Length, Got_Seed : Boolean := False;
Last : Positive;
Index : Positive := 1;
begin
Success := False;
if Argument_Count = 1 and then Argument (1) = "help" then
Config_Show_Help := True;
return;
end if;
 
while Index <= Argument_Count loop
if Ada.Command_Line.Argument (Index) = "safe" then
if Got_Safe then
return;
end if;
Got_Safe := True;
Config_Safe := True;
Index := Index + 1;
elsif Argument (Index) = "count" then
if Got_Count then
return;
end if;
Got_Count := True;
Ada.Integer_Text_IO.Get (Item => Config_Count,
From => Argument (Index + 1),
Last => Last);
if Last /= Argument (Index + 1)'Last then
return;
end if;
Index := Index + 2;
elsif Argument (Index) = "length" then
if Got_Length then
return;
end if;
Got_Length := True;
Ada.Integer_Text_IO.Get (Item => Config_Length,
From => Argument (Index + 1),
Last => Last);
if Last /= Argument (Index + 1)'Last then
return;
end if;
if Config_Length < 4 then
return;
end if;
Index := Index + 2;
elsif Argument (Index) = "seed" then
if Got_Seed then
return;
end if;
Got_Seed := True;
Ada.Integer_Text_IO.Get (Item => Config_Seed,
From => Argument (Index + 1),
Last => Last);
if Last /= Argument (Index + 1)'Last then
return;
end if;
Index := Index + 2;
else
return;
end if;
end loop;
Success := True;
exception
when Constraint_Error | Ada.Text_IO.Data_Error =>
null;
end Parse_Command_Line;
 
function Create_Password (Length : in Positive;
Safe : in Boolean)
return String
is
 
function Get_Random (Safe : in Boolean)
return Character;
 
function Get_Random (Safe : in Boolean)
return Character
is
use Ada.Strings.Fixed;
C : Character;
begin
loop
C := Full_Set (Full_Index_Generator.Random (Index_Generator));
if Safe then
exit when Index (Source => Unsafe_Set, Pattern => "" & C) = 0;
else
exit;
end if;
end loop;
return C;
end Get_Random;
 
function Has_Four (Item : in String)
return Boolean;
 
function Has_Four (Item : in String)
return Boolean
is
use Ada.Strings.Fixed;
Has_Upper, Has_Lower : Boolean := False;
Has_Digit, Has_Spec : Boolean := False;
begin
for C of Item loop
if Index (Upper_Set, "" & C) /= 0 then Has_Upper := True; end if;
if Index (Lower_Set, "" & C) /= 0 then Has_Lower := True; end if;
if Index (Digit_Set, "" & C) /= 0 then Has_Digit := True; end if;
if Index (Spec_Set, "" & C) /= 0 then Has_Spec := True; end if;
end loop;
return Has_Upper and Has_Lower and Has_Digit and Has_Spec;
end Has_Four;
 
Password : String (1 .. Length);
begin
loop
for I in Password'Range loop
Password (I) := Get_Random (Safe);
end loop;
exit when Has_Four (Password);
end loop;
return Password;
end Create_Password;
 
Parse_Success : Boolean;
begin
 
Parse_Command_Line (Parse_Success);
 
if Config_Show_Help or not Parse_Success then
Put_Usage; return;
end if;
 
if Config_Seed = 0 then
Full_Index_Generator.Reset (Index_Generator);
else
Full_Index_Generator.Reset (Index_Generator, Config_Seed);
end if;
 
for Count in 1 .. Config_Count loop
Ada.Text_IO.Put_Line (Create_Password (Length => Config_Length,
Safe => Config_Safe));
end loop;
 
end Mkpw;</syntaxhighlight>
{{out}}
<pre>$ ./mkpw count 8 length 22 safe
">M<P]GMHf77cbT%b8.eX]
W3Q&k~L*R,z)39(a{AvGon
3Xvh=:P9BGGU$=YPD{dFW@
^X)]vV4fFtCXksgv+,usHx
$89*bxyb?@aQEQ8~~vaq9o
FW{F*-]tDJH~]/7CLtRe-k
6%K6(8&fyX=,&TBFvW%kz3
+@pyJ'3YQ'%~9?Tm/BHk?A</pre>
 
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="applesoft">1 N=1
2 L=8
3 M$=CHR$(13)
4 D$=CHR$(4)
5 S$(0)="S"
6 F$="A FILE"
7 C$(1)=" (CURRENT OPTION)"
8 DEF FN R(T)=ASC(MID$(G$(T),INT(RND(1)*LEN(G$(T))+1),1))
9 GOSUB 750
10 FOR Q = 0 TO 1 STEP 0
20 GOSUB 50CHOOSE
30 NEXT Q
40 END
 
REM *** CHOOSE ***
50 PRINT M$M$"1 GEN 2 DISP 3 FILE 4 LEN 5 NUM 6 SEED"
60 PRINT "7 CHR 8 HELP 9 QUIT "CHR$(10)"CHOOSE AN OPTION: ";
70 GET K$
75 IF K$ > CHR$(95) THEN K$ = CHR$(ASC(K$) - 32)
80 PRINT K$
85 ON VAL(K$) GOTO 100,200,300,400,500,600,700,800,900
90 GOTO 210OPTIONS
 
REM *** GENERATE ***
100 PRINT M$
105 IF L > 32 THEN PRINT "UM... OK, THIS MIGHT TAKE A BIT."M$
110 GOSUB 340OPEN
115 FOR P=1 TO N
120 P$=""
125 FOR I=1 TO L
135 P$=P$+CHR$(FNR(I*(I<5)))
140 NEXT I
REM SHUFFLE FIRST 4
150 FOR I = 1 TO 4
151 C$=MID$(P$,I,1)
152 J=INT(RND(1)*L)+1
153 H$=MID$(P$,J,1)
154 P$=MID$(P$,1,J-1)+C$+MID$(P$,J+1,L)
155 P$=MID$(P$,1,I-1)+H$+MID$(P$,I+1,L)
156 NEXT I
180 PRINT P$
185 NEXT P
190 GOTO 380CLOSE
 
REM *** DISPLAY ***
200 C = 0
REM *** OPTIONS ***
210 HOME
215 PRINT "PASSWORD GENERATOR"M$M$
220 PRINT "1. GENERATE "N" PASSWORD"S$(N=1)M$
225 PRINT "2. DISPLAYED"C$(C=0)M$" OR"
230 PRINT "3. WRITTEN TO "F$C$(C=1)M$
235 PRINT "4. SPECIFY THE PASSWORD LENGTH = "L;M$
240 PRINT "5. SPECIFY THE NUMBER OF PASSWORDS TO"M$TAB(31)"GENERATE"
245 PRINT "6. SPECIFY A SEED VALUE"M$
250 PRINT "7. EXCLUDE VISUALLY SIMILAR CHARACTERS"M$
255 PRINT "8. HELP AND OPTIONS"
260 RETURN
 
REM *** WRITE TO A FILE ***
300 C = 1
310 GOTO 210OPTIONS
REM *** OPEN A FILE ***
340 IF NOT C THEN RETURN
345 PRINT D$"OPEN "F$"
350 PRINT D$"CLOSE"F$
355 PRINT D$"DELETE "F$
360 PRINT D$"OPEN "F$
365 PRINT D$"WRITE "F$
370 RETURN
REM *** CLOSE A FILE ***
380 IF NOT C THEN RETURN
385 PRINT D$"CLOSE"F$
390 RETURN
 
REM *** SET PASSWORD LENGTH ***
400 PRINT M$
410 FOR I = 0 TO 1 STEP 0
420 INPUT "ENTER A NUMBER FROM 4 TO 255 TO SPECIFY THE PASSWORD LENGTH = ";L
430 IF L >= 4 AND L < 256 THEN RETURN
440 PRINT "?OUT OF RANGE"
450 NEXT I
 
REM *** SET NUMBER OF PASSWORDS TO GENERATE ***
500 PRINT M$
510 FOR I = 0 TO 1 STEP 0
520 INPUT "ENTER A NUMBER FROM 1 AND UP TO SPECIFY THE NUMBER OF PASSWORDS TO GENERATE: ";N
530 IF N >= 1 THEN RETURN
540 PRINT "?OUT OF RANGE."
550 NEXT I
 
REM *** SET A SEED VALUE ***
600 PRINT M$
610 INPUT "ENTER A SEED VALUE: ";S%
620 PRINT RND(S%)
630 RETURN
 
REM *** EXCLUDE ***
700 PRINT M$
705 INPUT "ENTER CHARACTERS TO EXCLUDE:";E$
REM *** GROUPS ***
REM ALWAYS EXCLUDE BACKSLASH AND BACKTICK (GRAVE)
710 E$=CHR$(92)+CHR$(96)+E$
711 FOR G = 1 TO 4
712 G$(G) = ""
713 NEXT G
720 FOR G = 1 TO 2
721 FOR K = ASC("A") + (G - 1) * 32 TO ASC("Z") + (G - 1) * 32
722 GOSUB 770ADD
723 NEXT K, G
730 FOR K = 33 TO 64
731 G = 3 + (K < ASC(STR$(0)) OR K > ASC(STR$(9)))
732 GOSUB 770ADD
733 NEXT K
734 FOR K = 91 TO 96
735 GOSUB 770ADD
736 NEXT K
737 FOR K = 123 TO 126
738 GOSUB 770ADD
739 NEXT K
740 G$(0) = ""
741 FOR G = 1 TO 4
742 IF LEN(G$(G)) THEN G$(0) = G$(0) + G$(G) : NEXT G : GOTO 800HELP
743 ?"THERE MUST BE AT LEAST ONE CHARUNRACTER IN EACH GROUP"
744 GOTO 705
REM *** DEFAULT (QUICK) ***
750 G$(1)="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
751 FOR I=97TO122:G$(2)=G$(2)+CHR$(I):NEXT
753 G$(3)="0123456789"
754 G$(4)="!"+CHR$(34)+"#$%&'()*+,-./:;<=>?@"+CHR$(91)+"]^"+CHR$(95)
755 FOR I=123TO126:G$(4)=G$(4)+CHR$(I):NEXTI
756 G$(0)=G$(0)+G$(1)+G$(2)+G$(3)
757 GOTO 210OPTIONS
REM *** ADD TO GROUP
770 C$ = CHR$(K)
775 FOR E = 1 TO LEN(E$)
780 IF C$ <> MID$(E$,E,1) THEN NEXT E : G$(G)=G$(G)+C$ : ?C$;
790 RETURN
 
REM *** HELP ***
800 HOME
805 PRINT "GENERATE PASSWORDS CONTAINING RANDOM"
810 PRINT "ASCII CHARACTERS FROM THESE GROUPS:"M$
815 PRINT " LOWERCASE UPPERCASE DIGIT OTHER"M$
820 PRINT " "LEFT$(G$(2),9)TAB(13)LEFT$(G$(1),9)TAB(23)LEFT$(G$(3),5)TAB(29)LEFT$(G$(4),11)
825 PRINT " "MID$(G$(2),10,9)TAB(13)MID$(G$(1),10,9)TAB(23)MID$(G$(3),6,5)TAB(29)MID$(G$(4),12,11)
826 PRINT " "MID$(G$(2),19,9)TAB(13)MID$(G$(1),19,9)TAB(29)MID$(G$(4),23,15)M$
840 PRINT "YOU MAY CHOOSE THE PASSWORD LENGTH, AND"
845 PRINT "HOW MANY PASSWORDS TO GENERATE. IT IS"
850 PRINT "ENSURED THAT THERE IS AT LEAST ONE"
855 PRINT "CHARACTER FROM EACH OF THE GROUPS IN"
860 PRINT "EACH PASSWORD. THERE IS AN OPTION TO"
865 PRINT "EXCLUDE VISUALLY SIMILAR CHARACTERS."
870 RETURN
 
REM *** QUIT ***
900 Q = 1
910 VTAB 23
920 RETURN</syntaxhighlight>
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">lowercase: `a`..`z`
uppercase: `A`..`Z`
digits: `0`..`9`
other: map split "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" => [to :char]
 
any: lowercase ++ uppercase ++ digits ++ other
 
generate: function [length][
if length < 4 [
print (color #red "ERROR: ") ++ "password length too short"
exit
]
 
chars: new @[sample lowercase sample uppercase sample digits sample other]
while [length > size chars][
'chars ++ sample any
]
 
join shuffle chars
]
 
if 0 = size arg [
print {
---------------------------------
Arturo password generator
(c) 2021 drkameleon
---------------------------------
usage: passgen.art <length>
}
exit
]
 
loop 1..10 'x [
print generate to :integer first arg
]</syntaxhighlight>
 
{{out}}
 
<pre>; executed with ./passgen.art 10
 
T{6G7:qgyp
s7|iC2S0Tf
D6.Ac}1}oz
9**;81R@h<
H+|0CBN(ca
x!C#0yri]@
OfV7wlg*<G
{0z3MVJUNg
yULk,=B)84
C>o6]&9y<X</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f PASSWORD_GENERATOR.AWK [-v mask=x] [-v xt=x]
#
Line 133 ⟶ 1,010:
printf("example: %s -v mask=%s -v xt=%s\n",cmd,mask,xt)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 145 ⟶ 1,022:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 272 ⟶ 1,149:
return 0;
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 286 ⟶ 1,163:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 360 ⟶ 1,237:
return new string(password);
}
}</langsyntaxhighlight>
{{out}}
<pre>PASSGEN -l:12 -c:6
Line 371 ⟶ 1,248:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <algorithm>
Line 425 ⟶ 1,302:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 450 ⟶ 1,327:
<b>module.ceylon</b>:
 
<langsyntaxhighlight lang="ceylon">
module rosetta.passwordgenerator "1.0.0" {
import ceylon.random "1.2.2";
}
 
</syntaxhighlight>
</lang>
 
<b>run.ceylon:</b>
 
<langsyntaxhighlight lang="ceylon">
import ceylon.random {
DefaultRandom,
Line 592 ⟶ 1,469:
Character[] filterCharsToExclude(Character[] chars, Character[] charsToExclude)
=> chars.filter((char) => ! charsToExclude.contains(char)).sequence();
</syntaxhighlight>
</lang>
 
 
Line 632 ⟶ 1,509:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(ns pwdgen.core
(:require [clojure.set :refer [difference]]
[clojure.tools.cli :refer [parse-opts]])
Line 670 ⟶ 1,547:
(if (:help options) (println summary)
(dotimes [n (:count options)]
(println (apply str (generate-password options)))))))</langsyntaxhighlight>
 
{{out}}
Line 689 ⟶ 1,566:
Pj+4b
</pre>
 
=={{header|Commodore BASIC}}==
 
Note that on line 220, the <code>CLR</code> statement is called prior to restarting the program to avoid a <code>?REDIM'D ARRAY ERROR</code> if line 85 should execute. By default, single dimension arrays do not need to be DIMensioned if kept to 11 elements (0 through 10) or less. Line 85 checks for this.
 
<syntaxhighlight lang="gwbasic">1 rem password generator
2 rem rosetta code
10 g$(1)="abcdefghijklmnopqrstuvwxyz"
15 g$(2)="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
20 g$(3)="0123456789"
25 g$(4)="<>!@#$%^&*()[];:'.?/"
30 print chr$(147);chr$(14)
35 print "Password Generator":print
40 print "Press H for help, or any":print "other key to begin.":print
45 get k$:if k$="" then 45
50 if k$="h" then gosub 500
60 print chr$(147)
65 input "Enter password length: (6-30)";pl
70 if pl<6 or pl>30 then print "Out of range.":goto 65
75 print:input "How many passwords (1-20)";np
80 if np<1 or np>20 then print "Out of range.":goto 75
85 if np>10 then dim pw$(np)
90 if np*pl > 100 then print:print "Um... Ok, this might take a bit."
100 for pc=1 to np
105 for i=1 to 4:g(i)=0:next
110 tp$=""
112 for i=1 to pl
115 cg=int(rnd(1)*4)+1
120 cc=int(rnd(1)*len(g$(cg)))+1
125 tp$=tp$+mid$(g$(cg),cc,1)
130 g(cg)=g(cg)+1
135 next i
140 for i=1 to 4
145 if g(i)=0 then goto 110
150 next i
155 pw$(pc)=tp$
160 next pc
200 print chr$(147);"Password list:":print
205 for pc=1 to np:print pc;chr$(157);".";tab(6);pw$(pc):next pc
210 print:print "Again? (y/n)";
215 get k$:if k$<>"y" and k$<>"n" then 215
220 if k$="y" then clr:goto 10
225 end
500 rem *** help ***
505 print chr$(147);"This program will generate a password"
510 print "made up of each of the following"
515 print "character types:":print
520 print " - Uppercase Letter (A-Z)"
525 print " - Lowercase Letter (a-z)"
530 print " - Number (0-9)"
535 print " - Punctuation and Other Symbols"
540 print " (e.g. # $ ! & [ . ;, etc.)"
545 print
550 print "You may choose how many total characters";
555 print "(up to 30) should be in the password, "
560 print "and how many passwords (up to 20) should";
565 print "be generated. The program ensures that "
570 print "there is at least one character from "
575 print "each of the character types in each "
580 print "password."
585 print
590 print "Note: You can edit the character lists"
595 print "on lines 10-25 to customize the"
600 print "selection pool."
605 print
610 print "Press any key to begin."
615 get k$:if k$="" then 615
620 return</syntaxhighlight>
 
{{out}}
<pre>Password Generator
Press H for help, or any
other key to begin.
 
This program will generate a password
made up of each of the following
character types:
- Uppercase Letter (A-Z)
- Lowercase Letter (a-z)
- Number (0-9)
- Punctuation and Other Symbols
(e.g. # $ ! & [ . ;, etc.)
You may choose how many total characters
(up to 30) should be in the password,
and how many passwords (up to 20) should
be generated. The program ensures that
there is at least one character from
each of the character types in each
password.
Note: You can edit the character lists
on lines 10-25 to customize the
selection pool.
Press any key to begin.
Enter password length: (6-30)? 12
How many passwords (1-20)? 10
Um... Ok, this might take a bit.
 
Password list:
1. K6GmO#[%lz7w
2. L6W(ln<Qldvy
3. lc48].KX<F$w
4. 3$Z%;8/&70y5
5. <Ns@!W9#0[s3
6. )Sr!oZ<1pS1I
7. mhC4VTy]6a:7
8. !j4ntp8lJ1JY
9. ?b?1x48m$D65
10. Ooi;3W>[gr77
Again? (y/n)
ready.
&#9608;</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defvar *lowercase* '(#\a #\b #\c #\d #\e #\f #\g #\h #\i #\j #\k #\l #\m
#\n #\o #\p #\q #\r #\s #\t #\u #\v #\w #\x #\y #\z))
Line 738 ⟶ 1,736:
(loop for x from 1 to count do
(print (generate-password len human-readable)))))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 751 ⟶ 1,749:
 
=={{header|Crystal}}==
<langsyntaxhighlight Crystallang="crystal">require "random/secure"
 
special_chars = true
Line 822 ⟶ 1,820:
break if count <= 0
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 869 ⟶ 1,867:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Password do
@lower Enum.map(?a..?z, &to_string([&1]))
@upper Enum.map(?A..?Z, &to_string([&1]))
Line 907 ⟶ 1,905:
end
 
Password.generator</langsyntaxhighlight>
 
{{out}}
Line 924 ⟶ 1,922:
=={{header|F_Sharp|F#}}==
===The function===
<langsyntaxhighlight lang="fsharp">
// A function to generate passwords of a given length. Nigel Galloway: May 2nd., 2018
let N = (set)"qwertyuiopasdfghjklzxcvbnm"
Line 935 ⟶ 1,933:
let fN n = not (Set.isEmpty (Set.intersect N n )||Set.isEmpty (Set.intersect I n )||Set.isEmpty (Set.intersect G n )||Set.isEmpty (Set.intersect E n ))
Seq.initInfinite(fun _->(set)(List.init n (fun _->L.[y.Next()%(Array.length L)])))|>Seq.filter fN|>Seq.map(Set.toArray >> System.String)
</syntaxhighlight>
</lang>
===A possible use===
Print 5 password of length 8
<langsyntaxhighlight lang="fsharp">
pWords 8 |> Seq.take 5 |> Seq.iter(printfn "%s")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 952 ⟶ 1,950:
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<langsyntaxhighlight lang="factor">USING: arrays assocs combinators command-line continuations io
kernel math math.parser multiline namespaces peg.ebnf
prettyprint random sequences ;
Line 1,021 ⟶ 2,019:
[ parse-args gen-pwds ] [ 2drop usage print ] recover ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 1,043 ⟶ 2,041:
9L6Lqt|yh|
</pre>
 
 
=={{header|FreeBASIC}}==
{{trans|Run BASIC}}<syntaxhighlight lang="freebasic">Dim As String charS(4)
charS(1) = "0123456789"
charS(2) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
charS(3) = "abcdefghijklmnopqrstuvwxyz"
charS(4) = "!""#$%&'()*+,-./:;<=>?@[]^_{|}~"
charS(0) = charS(1) + charS(2) + charS(3) + charS(4)
 
 
Dim As Integer howBig, howMany
Do
Print !"------ Password Generator ------\n"
Input "Longitud de la contrase¤a (n>=4): ", howBig
If howBig < 1 Then Sleep: End
Input "Cantidad de contrase¤as (n>=1): ", howMany
Loop While howMany < 1
 
Print !"\nGeneradas"; howMany; " contrase¤as de"; howBig; " caracteres"
 
Dim As Integer i = 0
Dim As String password, Ok, w
While i < howMany
password = ""
Ok = "...."
For j As Integer = 1 To howBig
w = Mid(charS(0), Int(Rnd * Len(charS(0))) + 1, 1)
For k As Byte = 1 To 4
If Instr(charS(k), w) Then Ok = Left(Ok, k-1) + "*" + Mid(Ok, k+1)
Next k
password += w
Next j
If Ok = "****" Then
i += 1
Print Using "##. &"; i; password
End If
Wend
Sleep
</syntaxhighlight>
{{out}}
<pre>------ Password Generator ------
 
Longitud de la contraseña (n>=4): 5
Cantidad de contraseñas (n>=1): 2
 
Generadas 2 contraseñas de 5 caracteres
1. 1qU+,
2. v?X7s
</pre>
 
=={{header|FutureBasic}}==
This compiles as a standalone Mac application that meets all the task requirements and options. Screenshot of compiled app shows output.
<syntaxhighlight lang="futurebasic">
output file "Password Generator"
include "Tlbx GameplayKit.incl"
 
begin enum
_mApplication
_mFile
_mEdit
end enum
 
begin enum 1
_iSeparator
_iPreferences
end enum
 
begin enum
_iCreate
_iSeparator2
_iSave
_iPrint
_iSeparator4
_iClose
end enum
 
_window = 1
begin enum output 1
_passwordScroll
_passwordView
_offscreenPrintView
_optionsHelp
_checkOmitIs
_checkOmitOs
_checkOmitSs
_checkOmit2s
_charactersLongLabel
_passwordLengthField
_pwAmountLabel
_pwAmountField
_seedLabel
_seedField
_helpBtn
_bottomLine
_saveBtn
_printBtn
_createPasswordsBtn
end enum
 
_helpPopover = 2
begin enum 1
_popoverLabel
end enum
 
_savePanel = 1
_pwLenAlert = 2
 
 
void local fn BuildMenus
// application
menu _mApplication, _iSeparator
menu _mApplication, _iPreferences,, @"Preferences…", @","
// file
menu _mFile, -1,, @"File"
menu _mFile, _iCreate,, @"Create passwords", @"p"
menu _mFile, _iSeparator2
menu _mFile, _iSave,, @"Save", @"s"
menu _mFile, _iPrint,, @"Print", @"p"
menu _mFile, _iSeparator4
menu _mFile, _iClose,, @"Close", @"w"
MenuItemSetAction( _mFile, _iClose, @"performClose:" )
editmenu _mEdit
end fn
 
void local fn BuildWindow
long tag
CGRect r = fn CGRectMake( 0, 0, 672, 460 )
window _window, @"Rosetta Code Password Generator", r//, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + NSWindowStyleMaskMiniaturizable
WindowSetContentMinSize( _window, fn CGSizeMake(310,386) )
r = fn CGRectMake( 20, 73, 515, 370 )
scrollview _passwordScroll, r, NSLineBorder,,_window
ViewSetAutoresizingMask( _passwordScroll, NSViewWidthSizable + NSViewHeightSizable )
textview _passwordView, r, _passwordScroll,, _window
TextViewSetTextContainerInset( _passwordView, fn CGSizeMake( 10, 15 ) )
TextSetFontWithName( _passwordView, @"Menlo", 13.0 )
r = fn CGRectMake( -600, -600, 450, 405 )
textview _offscreenPrintView, r,,, _window
TextSetFontWithName( _offscreenPrintView, @"Menlo", 13.0 )
TextSetColor( _offscreenPrintView, fn ColorBlack )
TextViewSetBackgroundColor( _offscreenPrintView, fn ColorWhite )
r = fn CGRectMake( 547, 424, 60, 16 )
textlabel _optionsHelp, @"Exclude:", r, _window
r = fn CGRectMake( 607, 425, 41, 14 )
button _checkOmitIs, YES, NSControlStateValueOff, @"Il1", r, NSButtonTypeSwitch
ViewSetToolTip( _checkOmitIs, @"Omit similar characters I, l and 1." )
r = fn CGRectOffset( r, 0, -24 )
button _checkOmitOs, YES ,NSControlStateValueOff, @"O0", r, NSButtonTypeSwitch
ViewSetToolTip( _checkOmitOs, @"Omit similar characters O and 0." )
r = fn CGRectOffset( r, 0, -24 )
button _checkOmitSs, YES, NSControlStateValueOff, @"5S", r, NSButtonTypeSwitch
ViewSetToolTip( _checkOmitSs, @"Omit similar characters 5 and S." )
r = fn CGRectOffset( r, 0, -24 )
button _checkOmit2s, YES, NSControlStateValueOff, @"2Z", r, NSButtonTypeSwitch
ViewSetToolTip( _checkOmit2s, @"Omit similar characters 2 and Z." )
r = fn CGRectMake( 549, 322, 103, 16 )
textlabel _charactersLongLabel, @"Chars (4-50)", r, _window
r = fn CGRectMake( 549, 298, 103, 21 )
textfield _passwordLengthField, YES, @"25", r,_window
TextFieldSetBordered( _passwordLengthField, YES )
ControlSetAlignment(_passwordLengthField, NSTextAlignmentCenter )
ControlSetFormat( _passwordLengthField, @"0123456789", YES, 2, 0 )
ViewSetToolTip( _passwordLengthField, @"Set password length from 4 to 50." )
r = fn CGRectMake( 549, 263, 103, 16 )
textlabel _pwAmountLabel, @"Passwords:", r, _window
r = fn CGRectMake( 549, 240, 103, 21 )
textfield _pwAmountField, YES, @"100", r,_window
TextFieldSetBordered( _pwAmountField, YES )
ControlSetAlignment( _pwAmountField, NSTextAlignmentCenter )
ControlSetFormat( _pwAmountField, @"0123456789", YES, 4, 0 )
ViewSetToolTip( _pwAmountField, @"Enter number of passwords to generate." )
r = fn CGRectMake( 549, 205, 103, 16 )
textlabel _seedLabel, @"Seed value:", r, _window
r = fn CGRectMake( 549, 182, 103, 21 )
textfield _seedField, YES, , r,_window
TextFieldSetBordered( _seedField, YES )
ControlSetAlignment(_seedField, NSTextAlignmentCenter )
ControlSetFormat( _seedField, @"0123456789", YES, 6, 0 )
ViewSetToolTip( _seedField, @"Enter optional random seed number." )
for tag = _optionsHelp to _seedField
ViewSetAutoresizingMask( tag, NSViewMinXMargin + NSViewMinYMargin )
next
r = fn CGRectMake( 631, 70, 25, 25 )
button _helpBtn, YES,,, r, NSButtonTypeMomentaryLight, NSBezelStyleHelpButton, _window
ViewSetToolTip( _helpBtn, @"Click for application help instructions." )
ViewSetAutoresizingMask( _helpBtn, NSViewMinXMargin + NSViewMaxYMargin )
r = fn CGRectMake( 20, 55, 632, 5 )
box _bottomline,, r, NSBoxSeparator
ViewSetAutoresizingMask( _bottomline, NSViewWidthSizable + NSViewMaxYMargin )
r = fn CGRectMake( 20, 15, 62, 32 )
button _printBtn, YES, , @"Print…", r, NSButtonTypeMomentaryLight, NSBezelStyleRegularSquare, _window
ViewSetAutoresizingMask( _printBtn, NSViewMaxXMargin + NSViewMaxYMargin )
r = fn CGRectMake( 91, 15, 62, 32 )
button _saveBtn, YES, , @"Save…", r, NSButtonTypeMomentaryLight, NSBezelStyleRegularSquare, _window
ViewSetAutoresizingMask( _saveBtn, NSViewMaxXMargin + NSViewMaxYMargin )
r = fn CGRectMake( 522, 15, 131, 32 )
button _createPasswordsBtn, YES, , @"Create passwords", r, NSButtonTypeMomentaryLight, NSBezelStyleRegularSquare, _window
ViewSetAutoresizingMask( _createPasswordsBtn, NSViewMinXMargin + NSViewMaxYMargin )
end fn
 
void local fn BuildPopover
CFStringRef helpText = @"This application generates randomized passwords from 4 to 50 characters in length. "
helpText = fn StringByAppendingString( helpText, @"Theoretically, the number generated is limited only by system memory.\n\n" )
helpText = fn StringByAppendingString( helpText, @"Passwords will contain at least one each of the following character types:\n" )
helpText = fn StringByAppendingString( helpText, @"\tLowercase letters\t\t: a -> z\n" )
helpText = fn StringByAppendingString( helpText, @"\tUppercase letters\t\t: A -> Z\n" )
helpText = fn StringByAppendingString( helpText, @"\tNumbers\t\t\t\t: 0 -> 9\n" )
helpText = fn StringByAppendingString( helpText, @"\tSpecial characters\t: !\"#$%&'()*+,-./:;<=>?@[]^_{|}~\n\n" )
helpText = fn StringByAppendingString( helpText, @"You can use checkboxes to exclude visually similar characters: Il1 O0 5S 2Z.\n\n" )
helpText = fn StringByAppendingString( helpText, @"This application offers two automatic levels of randomization. However you are " )
helpText = fn StringByAppendingString( helpText, @"welcome to enter a custom randomizer seed number in the box provided.\n\n" )
helpText = fn StringByAppendingString( helpText, @"Passwords can be copied to the pasteboard, saved to a text file, or printed." )
popover _helpPopover, (0,0,395,365), NSPopoverBehaviorTransient
textlabel _popoverLabel, helpText, (10,10,375,345)
end fn
 
void local fn OutOfBoundsAlert
CFStringRef alertStr = @"Passwords must be at least four characters long, but no more than 50 characters."
alert -_pwLenAlert,, @"Password length is out of bounds", alertStr, @"Okay", YES
AlertButtonSetKeyEquivalent( _pwLenAlert, 1, @"\e" )
AlertSetStyle( _pwLenAlert, NSAlertStyleWarning )
alert _pwLenAlert
end fn
 
 
local fn BuildPassword as CFStringRef
long i
CFArrayRef charArr = fn AppProperty( @"charArray" )
CFStringRef numbers = charArr[0]
CFStringRef uppercase = charArr[1]
CFStringRef lowercase = charArr[2]
CFStringRef symbols = charArr[3]
// Omit confusing letters selected by user, if any
if ( fn ButtonState( _checkOmitIs ) == NSControlStateValueOn )
numbers = fn StringByReplacingOccurrencesOfString( numbers, @"1", @"" )
uppercase = fn StringByReplacingOccurrencesOfString( uppercase, @"I", @"" )
lowercase = fn StringByReplacingOccurrencesOfString( lowercase, @"l", @"" )
end if
if ( fn ButtonState( _checkOmitOs ) == NSControlStateValueOn )
numbers = fn StringByReplacingOccurrencesOfString( numbers, @"0", @"" )
uppercase = fn StringByReplacingOccurrencesOfString( uppercase, @"O", @"" )
end if
if( fn ButtonState( _checkOmitSs ) == NSControlStateValueOn )
numbers = fn StringByReplacingOccurrencesOfString( numbers, @"5", @"" )
uppercase = fn StringByReplacingOccurrencesOfString( uppercase, @"S", @"" )
end if
if ( fn ButtonState( _checkOmit2s ) == NSControlStateValueOn )
numbers = fn StringByReplacingOccurrencesOfString( numbers, @"2", @"" )
uppercase = fn StringByReplacingOccurrencesOfString( uppercase, @"Z", @"" )
end if
// Build string pool from other character sets
CFStringRef allChars = fn StringWithFormat( @"%@%@%@%@", numbers, uppercase, lowercase, symbols )
// Begin construction password string with single random character from each character set
randomize
CFMutableStringRef pwStr = fn MutableStringWithCapacity(0)
CFStringRef rndNumberChar = fn StringWithFormat( @"%c", fn StringCharacterAtindex( numbers, rnd( len( numbers ) -1 ) ) )
CFStringRef rndUCaseChar = fn StringWithFormat( @"%c", fn StringCharacterAtindex( uppercase, rnd( len( uppercase ) -1 ) ) )
CFStringRef rndLCaseChar = fn StringWithFormat( @"%c", fn StringCharacterAtindex( lowercase, rnd( len( lowercase ) -1 ) ) )
CFStringRef rndSymbolChar = fn StringWithFormat( @"%c", fn StringCharacterAtindex( symbols, rnd( len( symbols ) -1 ) ) )
// Add first four randomized characters to password string
MutableStringAppendString( pwStr, fn StringWithFormat( @"%@%@%@%@", rndNumberChar, rndUCaseChar, rndLCaseChar, rndSymbolChar ) )
// Build array of characters for shuffling
CFMutableArrayRef mutArr = fn MutableArrayWithCapacity(0)
for i = 0 to len(allChars) - 1
unichar tempUni = fn StringCharacterAtIndex( allChars, i )
CFStringRef s = fn StringWithFormat( @"%c", tempUni )
MutableArrayInsertObjectAtIndex( mutArr, s, i )
next
// Shuffle character array for randomness
CFArrayRef rndStrArr = fn GKRandomSourceArrayByShufflingObjectsInArray( fn GKRandomSourceInit, mutArr )
CFStringRef rndStr = fn ArrayComponentsJoinedByString( rndStrArr, @"" )
long pwLength = fn StringIntegerValue( fn ControlStringValue( _passwordLengthField ) )
// Subtract 4 for mandatory charaacters already set
rndStr = fn StringSubstringToIndex( rndStr, pwLength - 4 )
MutableStringAppendString( pwStr, rndStr )
end fn = pwStr
 
 
void local fn RandomizeWithSeed
CFStringRef seedStr = fn ControlStringValue( _seedField )
if ( len(seedStr) > 0 )
long seedNum = fn StringIntegerValue( seedStr )
randomize seedNum
else
exit fn
end if
end fn
 
 
void local fn CreatePasswords
NSInteger i
CFMutableStringRef passwords = fn MutableStringWithCapacity(0)
long numberNeeded = fn StringIntegerValue( fn ControlStringValue( _pwAmountField ) )
// Get length of password designated by user
long pwLength = fn StringIntegerValue( fn ControlStringValue( _passwordLengthField ) )
if ( pwLength > 50 ) or ( pwLength < 4 )
fn OutOfBoundsAlert : exit fn
end if
fn RandomizeWithSeed
for i = 1 to numberNeeded
MutableStringAppendString( passwords, fn StringWithFormat( @"%4d. %@%@\n", i, fn BuildPassword, @"\n" ) )
next
TextSetString( _passwordView, passwords )
end fn
 
 
void local fn SaveFile
savepanel -_savePanel, @"Save file...", @"public.plain-text",,,, _true
SavePanelSetCanCreateDirectories( _savePanel, YES )
SavePanelSetAllowedFileTypes( _savePanel, @[@"txt"] )
SavePanelSetExtensionHidden( _savePanel, NO )
// Run savepanel; action captured in fn DoDialog
savepanel _savePanel
end fn
 
 
void local fn SetViewText( url as CFURLRef )
CFStringRef tempStr = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )
WindowSetTitleWithRepresentedURL( _window, url )
TextSetString( _passwordView, tempStr )
end fn
 
 
void local fn PrintView( tag as long )
TextSetString( _offscreenPrintView, fn TextString( tag ) )
ViewPrint( _offscreenPrintView )
end fn
 
// Build character arrays at launch and save as application property
void local fn CreateCharactersDictionary
CFArrayRef charArray = @[¬
@"0123456789",¬
@"ABCDEFGHIJKLMNOPQRSTUVWXYZ",¬
@"abcdefghijklmnopqrstuvwxyz",¬
@"!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"]
AppSetProperty( @"charArray", charArray )
end fn
 
 
void local fn DoAppEvent( ev as long )
select (ev)
case _appDidFinishLaunching
fn CreateCharactersDictionary
fn BuildMenus
fn BuildPopover
fn BuildWindow
case _appShouldTerminateAfterLastWindowClosed
AppEventSetBool(YES)
end select
end fn
 
 
void local fn DoMenu( menuID as long, itemID as long )
select (menuID)
case _mApplication
select (itemID)
case _iPreferences // show preferences window
end select
case _mFile
select (itemID)
case _iCreate : fn CreatePasswords
case _iSave : fn SaveFile
case _iPrint : fn PrintView( _passwordView )
end select
end select
end fn
 
 
void local fn DoDialog( ev as NSInteger, tag as NSInteger, wnd as NSInteger, obj as CFTypeRef )
select ( ev )
case _btnClick
select ( tag )
case _createPasswordsBtn : fn CreatePasswords
case _saveBtn : fn SaveFile
case _printBtn : fn PrintView( _passwordView )
case _helpBtn : PopoverShow( _helpPopover, CGRectZero, _helpBtn, CGRectMaxXEdge )
end select
end select
end fn
 
on appEvent fn DoAppEvent
on menu fn DoMenu
on dialog fn DoDialog
 
HandleEvents
</syntaxhighlight>
{{output}}
[[File:Password Generator.png]]
 
=={{header|Gambas}}==
'''[https:c/gambas-playground.proko.eu/?gist=0ef1242c761d8a39297fb913fc6a56c0 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">' Gambas module file
 
' INSTRUCTIONS
Line 1,115 ⟶ 2,540:
Print sPassword 'Print the password list
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,135 ⟶ 2,560:
 
=={{header|Go}}==
<syntaxhighlight lang="go">
<lang Go>
package main
 
Line 1,228 ⟶ 2,653:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,246 ⟶ 2,671:
The function <code>password</code> for given length and a list of char sets which should be included, generates random password.
 
<langsyntaxhighlight Haskelllang="haskell">import Control.Monad
import Control.Monad.Random
import Data.List
Line 1,265 ⟶ 2,690:
x <- uniform lst
xs <- shuffle (delete x lst)
return (x : xs)</langsyntaxhighlight>
 
For example:
Line 1,277 ⟶ 2,702:
User interface (uses a powerful and easy-to-use command-line [https://hackage.haskell.org/package/options-1.2.1.1/docs/Options.html option parser]).
 
<langsyntaxhighlight Haskelllang="haskell">import Options
 
data Opts = Opts { optLength :: Int
Line 1,303 ⟶ 2,728:
, "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" ]
 
visualySimilar = ["l","IOSZ","012","!|.,"]</langsyntaxhighlight>
 
{{Out}}
Line 1,356 ⟶ 2,781:
Implementation:
 
<langsyntaxhighlight Jlang="j">thru=: <. + i.@(+*)@-~
chr=: a.&i.
 
Line 1,378 ⟶ 2,803:
y must be at least 4 because
passwords must contain four different kinds of characters.
)</langsyntaxhighlight>
 
Example use (from J command line):
 
<langsyntaxhighlight Jlang="j"> pwgen'help'
[x] pwgen y - generates passwords of length y
optional x says how many to generate (if you want more than 1)
Line 1,396 ⟶ 2,821:
Oo?|2oc4yi
9V9[EJ:Txs
$vYd(>4L:m</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|7}}
<langsyntaxhighlight lang="java">import java.util.*;
 
public class PasswordGenerator {
Line 1,465 ⟶ 2,890:
return sb.toString();
}
}</langsyntaxhighlight>
 
<pre>7V;m
Line 1,478 ⟶ 2,903:
*'R8yEmvh9v]</pre>
 
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">String.prototype.shuffle = function() {
return this.split('').sort(() => Math.random() - .5).join('');
}
 
function createPwd(opts = {}) {
let len = opts.len || 5, // password length
num = opts.num || 1, // number of outputs
noSims = opts.noSims == false ? false : true, // exclude similar?
out = [],
cur, i;
 
let chars = [
'abcdefghijkmnopqrstuvwxyz'.split(''),
'ABCDEFGHJKLMNPQRTUVWXY'.split(''),
'346789'.split(''),
'!"#$%&()*+,-./:;<=>?@[]^_{|}'.split('')
];
 
if (!noSims) {
chars[0].push('l');
chars[1] = chars[1].concat('IOSZ'.split(''));
chars[2] = chars[2].concat('1250'.split(''));
}
 
if (len < 4) {
console.log('Password length changed to 4 (minimum)');
len = 4;
}
 
while (out.length < num) {
cur = '';
// basic requirement
for (i = 0; i < 4; i++)
cur += chars[i][Math.floor(Math.random() * chars[i].length)];
 
while (cur.length < len) {
let rnd = Math.floor(Math.random() * chars.length);
cur += chars[rnd][Math.floor(Math.random() * chars[rnd].length)];
}
out.push(cur);
}
 
for (i = 0; i < out.length; i++) out[i] = out[i].shuffle();
 
if (out.length == 1) return out[0];
return out;
}
 
// testing
console.log( createPwd() );
console.log( createPwd( {len: 20}) );
console.log( createPwd( {len: 20, num: 2}) );
console.log( createPwd( {len: 20, num: 2, noSims: false}) );
</syntaxhighlight>
{{out}}<pre>
> Q^g"7
> NP3*fb3L!9++Yf)sx/m#
> Array [ "]7Qs9/7En9d,!!j.U6pT", "9LDc-is6tCa6L88dKy6H" ]
> Array [ "yI7<)d5a5#4R>v4aLG8.", "s<GJ59||J]vS%_gUf4Xs" ]
</pre>
 
 
=={{header|jq}}==
{{Works with|jq}}
 
'''Works with gojq, the Go implementation of jq'''
 
'''Adapted from [[#Julia|Julia]]'''
 
The following assumes that an external source of randomness such as /dev/urandom is available
and that jq is invoked along the lines of the following:
<pre>
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRnr -f password-generator.jq
</pre>
<syntaxhighlight lang="jq">
# Output: a prn in range(0;$n) where $n is `.`
def prn:
if . == 1 then 0
else . as $n
| ([1, (($n-1)|tostring|length)]|max) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
 
# Input: an array
# Output: an array, being a selection of $k elements from . chosen with replacement
def prns($k):
. as $in
| length as $n
| [range(0; $k) | $in[$n|prn]];
 
def knuthShuffle:
length as $n
| if $n <= 1 then .
else {i: $n, a: .}
| until(.i == 0;
.i += -1
| (.i + 1 | prn) as $j
| .a[.i] as $t
| .a[.i] = .a[$j]
| .a[$j] = $t)
| .a
end;
 
# Generate a single password of length $len >= 4;
# certain confusable characters are only allowed iff $simchars is truthy.
def passgen($len; $simchars):
def stoa: explode | map([.]|implode);
if $len < 4 then "length must be at least 4" | error
else
{ DIGIT: ("0123456789" | stoa),
UPPER: [range(65;91) | [.] | implode], # A-Z
LOWER: [range(97;123) | [.] | implode], # a-z
OTHER: ("!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" | stoa) }
| if $simchars|not
then .DIGIT |= . - ["0", "1", "2", "5"]
| .UPPER |= . - ["O", "I", "Z", "S"]
| .LOWER |= . - ["l"]
end
| (reduce (.DIGIT, .UPPER, .LOWER, .OTHER) as $set ([];
. + ($set | prns(1)))) +
(.DIGIT + .UPPER + .LOWER + .OTHER | prns($len - 4))
| knuthShuffle
| join("")
end ;
 
def passgen($len):
passgen($len; true);
 
# Generate a stream of $npass passwords, each of length $len;
# certain confusable characters are only allowed iff $simchars is truthy.
def passgen($len; $npass; $seed; $simchars):
if ($seed | type) == "number" and $seed > 0 then $seed | prn else null end
| range(0; $npass)
| passgen($len; $simchars) ;
 
 
### Examples:
"Without restriction:", passgen(12; 5; null; true),
"",
"Certain confusable characters are disallowed:", passgen(12; 5; null; false)
</syntaxhighlight>
{{output}}
<pre>
Without restriction:
yT8+9t7=wfEn
#]j<HIpThJ6A
|~O{psk*[5)I
w_(N%QrI5:5#
$o3sfdKv"'9~
 
Certain confusable characters are disallowed:
>oXgj>H9wX^[
a^JR+v!bk6GU
7$~yp?YG]G|E
!/_MM_g.p{a4
iD?+xU+!A4]R
</pre>
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function passgen(len::Integer; simchars::Bool=true)::String
if len < 4; error("length must be at least 4") end
# Definitions
Line 1,509 ⟶ 3,094:
end
 
passgen(stdout, 10, 12; seed = 1)</langsyntaxhighlight>
 
{{out}}
Line 1,526 ⟶ 3,111:
 
=={{header|Kotlin}}==
<langsyntaxhighlight Groovylang="groovy">// version 1.1.4-3
 
import java.util.Random
Line 1,716 ⟶ 3,301:
generatePasswords(pwdLen!!, pwdNum!!, toConsole, toFile!!)
}</langsyntaxhighlight>
 
Sample input and output:
Line 1,748 ⟶ 3,333:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function randPW (length)
local index, pw, rnd = 0, ""
local chars = {
Line 1,777 ⟶ 3,362:
os.exit()
end
for i = 1, arg[2] do print(randPW(tonumber(arg[1]))) end</langsyntaxhighlight>
Command line session:
<pre>>lua pwgen.lua
Line 1,795 ⟶ 3,380:
6lN9*Nx<</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">(* Length is the Length of the password, num is the number you want, \
 
<lang Mathematica>
(* Length is the Length of the password, num is the number you want, \
and similar=1 if you want similar characters, 0 if not. True and \
False, should work in place of 1/0 *)
Line 1,828 ⟶ 3,411:
]</syntaxhighlight>
]
 
</lang>
=={{header|Nim}}==
<syntaxhighlight lang="nim">import os, parseopt, random, sequtils, strformat, strutils
 
const Symbols = toSeq("!\"#$%&'()*+,-./:;<=>?@[]^_{|}~")
 
 
proc passGen(passLength = 10,
count = 1,
seed = 0,
excludeSimilars = false): seq[string] =
## Generate a sequence of passwords.
 
# Initialize the random number generator.
if seed == 0: randomize()
else: randomize(seed)
 
# Prepare list of chars per category.
var
lowerLetters = toSeq('a'..'z')
upperLetters = toSeq('A'..'Z')
digits = toSeq('0'..'9')
 
if excludeSimilars:
lowerLetters.delete(lowerLetters.find('l'))
for c in "IOSZ": upperLetters.delete(upperLetters.find(c))
for c in "012": digits.delete(digits.find(c))
 
let all = lowerLetters & upperLetters & digits & Symbols
 
# Generate the passwords.
for _ in 1..count:
var password = newString(passLength)
password[0] = lowerLetters.sample
password[1] = upperLetters.sample
password[2] = digits.sample
password[3] = Symbols.sample
for i in 4..<passLength:
password[i] = all.sample
password.shuffle()
result.add password
 
 
proc printHelp() =
## Print the help message.
echo &"Usage: {getAppFileName().lastPathPart} " &
"[-h] [-l:length] [-c:count] [-s:seed] [-x:(true|false)]"
echo " -h: display this help"
echo " -l: length of generated passwords"
echo " -c: number of passwords to generate"
echo " -s: seed for the random number generator"
echo " -x: exclude similar characters"
 
 
proc getIntValue(key, val: string): int =
## Get a positive integer value from a string.
try:
result = val.parseInt()
if result <= 0:
raise newException(ValueError, "")
except ValueError:
quit &"Wrong value for option -{key}: {val}", QuitFailure
 
 
var
passLength = 10
count = 1
seed = 0
excludeSimilars = false
 
# Process options.
var parser = initOptParser()
 
for kind, key, val in parser.getopt():
if kind != cmdShortOption:
printHelp()
quit(QuitFailure)
 
case key
of "h":
printHelp()
quit(QuitSuccess)
of "l":
passLength = getIntValue(key, val)
of "c":
count = getIntValue(key, val)
of "s":
seed = getIntValue(key, val)
of "x":
if val.toLowerAscii == "true":
excludeSimilars = true
elif val.toLowerAscii == "false":
excludeSimilars = false
else:
quit &"Wrong value for option -x: {val}", QuitFailure
else:
quit &"Wrong option: -{key}"
 
# Display the passwords.
for pw in passGen(passLength, count, seed, excludeSimilars):
echo pw</syntaxhighlight>
 
{{out}}
<pre>$ ./passgen -c:6
hG']0ipc7P
1|"AjJDYxe
VwU'!7<+!<
=Do]49_vd5
4lqrr>B*X1
8J1_J#>hi7</pre>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let lower = "abcdefghijklmnopqrstuvwxyz"
let upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let digit = "0123456789"
let other = "!\"034#$%&'()*+,-./:;<=>?@[]^_{|}~"
(* unconfuse syntax highlighter: " *)
 
let visually_similar = "Il1O05S2Z"
Line 1,890 ⟶ 3,581:
for i = 1 to !num do
print_endline (mk_pwd !len !readable)
done</langsyntaxhighlight>
 
{{out}}
Line 1,912 ⟶ 3,603:
=={{header|ooRexx}}==
{{trans||REXX}}
<langsyntaxhighlight lang="oorexx">/*REXX program generates a random password according to the Rosetta Code task's rules.*/
parse arg L N seed xxx dbg /*obtain optional arguments from the CL*/
casl= 'abcdefghijklmnopqrstuvwxyz' /*define lowercase alphabet. */
Line 2,009 ⟶ 3,700:
¦ dbg Schow count of characters in the 4 groups ¦
+-----------------------------------------------------------------------------+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~documentation ends on the previous line.~~~~~~~~~~~~~~~~~~~*/</langsyntaxhighlight>
{{out}}
<pre>D:\>rexx genpwd 12 4 33 , x
Line 2,034 ⟶ 3,725:
 
PARI/GP has a very good builtin random generator.
<langsyntaxhighlight lang="parigp">passwd(len=8, count=1, seed=0) =
{
if (len <= 4, print("password too short, minimum len=4"); return(), seed, setrand(seed));
Line 2,048 ⟶ 3,739:
}
 
addhelp(passwd, "passwd({len},{count},{seed}): Password generator, optional: len (min=4, default=8), count (default=1), seed (default=0: no seed)");</langsyntaxhighlight>
 
Output: ''passwd()''<pre>34K76+mB</pre>
Line 2,068 ⟶ 3,759:
 
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">
<lang PASCAL>
program passwords (input,output);
 
Line 2,245 ⟶ 3,936:
end.
 
</syntaxhighlight>
</lang>
Useage for the output example: passwords --about -h --length=12 --number 12 --exclude
 
Line 2,279 ⟶ 3,970:
 
=={{header|Perl}}==
Use the module <tt>Math::Random</tt> for marginally better random-ness than the built-in function, but no warranty is expressed or implied, <i>caveat emptor</i>.
We use Math::Random, for two reasons: 1) we can use its random_permutation() function; 2) there is a security aspect to this task, so we should avoid using the built-in rand() function as it is presumably less sophisticated.
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
 
use English;
use Const::Fast;
use Getopt::Long;
use Math::Random;
 
my $pwd_length = 8;
my $num_pwds = 6;
my $seed_phrase = 'TOO MANY SECRETS';
my %opts = ('password_length=i' => \$pwd_length,
'num_passwords=i' => \$num_pwds,
'seed_phrase=s' => \$seed_phrase,
'help!' => sub {command_line_help(); exit 0;});
if (! GetOptions(%opts)) {command_line_help(); exit 1; }
$num_pwds >= 1 or die "Number of passwords must be at least 1";
$pwd_length >= 4 or die "Password length must be at least 4";
random_set_seed_from_phrase($seed_phrase);
 
const my @lcs => 'a' .. 'z';
const my @ucs => 'A' .. 'Z';
const my @digits => 0 .. 9;
const my $others => q{!"#$%&'()*+,-./:;<=>?@[]^_{|}~}; # "
 
# Oh syntax highlighter, please be happy once more "
my $pwd_length = 8;
foreach my $i (1 .. $num_pwds) {
my $num_pwds = 6;
print gen_password(), "\n";
my $seed_phrase = 'TOO MANY SECRETS';
}
 
exit 0;
my %opts = (
'password_length=i' => \$pwd_length,
'num_passwords=i' => \$num_pwds,
'seed_phrase=s' => \$seed_phrase,
'help!' => sub {command_line_help(); exit 0}
);
command_line_help() and exit 1 unless $num_pwds >= 1 and $pwd_length >= 4 and GetOptions(%opts);
 
random_set_seed_from_phrase($seed_phrase);
say gen_password() for 1 .. $num_pwds;
 
sub gen_password {
my @generators = (\&random_lc, \&random_uc, \&random_digit, \&random_other);
my @chars = map {$ARG->()} @generators; # At least one char of each type.
forpush (my@chars, $j =generators[random_uniform_integer(1, 0;, $j3)]->() <for 1 .. $pwd_length - 4; $j++) {
join '', random_permutation(@chars);
my $one_of_four = random_uniform_integer(1, 0, 3);
push @chars, $generators[$one_of_four]->();
}
return join(q{}, random_permutation(@chars));
}
 
sub random_lc { $lcs[ random_uniform_integer(1, 0, $#lcs) ] }
sub random_uc my $idx{ = $ucs[ random_uniform_integer(1, 0, scalar(@lcs$#ucs)-1); ] }
sub random_digit { $digits[ random_uniform_integer(1, 0, $#digits) ] }
return $lcs[$idx];
sub random_other { substr($others, random_uniform_integer(1, 0, length($others)-1), 1) }
}
 
sub random_uc {
my $idx = random_uniform_integer(1, 0, scalar(@ucs)-1);
return $ucs[$idx];
}
 
sub random_digit {
my $idx = random_uniform_integer(1, 0, scalar(@digits)-1);
return $digits[$idx];
}
 
sub random_other {
my $idx = random_uniform_integer(1, 0, length($others)-1);
return substr($others, $idx, 1);
}
 
sub command_line_help {
say <<~END
print "Usage: $PROGRAM_NAME ",
Usage: $PROGRAM_NAME
"[--password_length=<l> (default: $pwd_length)] ",
"[--num_passwordspassword_length=<nl> (default: $num_pwds)8, minimum: 4] ",
"[--seed_phrasenum_passwords=<sn> ( default: $seed_phrase)] "6, minimum: 1]
[--seed_phrase=<s> default: TOO MANY SECRETS (optional)]
"[--help]\n";
return; [--help]
END
}</lang>
}</syntaxhighlight>
Transcript (with paths redacted):
{{out}}
<pre>...>password_generator.pl --help
<pre>sc3O~3e0
Usage: ...\password_generator.pl [--password_length=<l> (default: 8)] [--num_passwords=<n> (default: 6)] [--seed_phrase=<s> (default: TOO MANY SECRETS)] [--help]
 
...>password_generator.pl
sc3O~3e0
pE{uh7)%
3J:'L)x8
Line 2,359 ⟶ 4,030:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence az = "abcdefghijklmnopqrstuvwxyz",
<span style="color: #000080;font-style:italic;">--with javascript_semantics -- not quite yet:</span>
AZ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (VALUECHANGED_CB not yet triggering)</span>
O9 = "1234567890",
<span style="color: #008080;">constant</span> <span style="color: #000000;">az</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"abcdefghijklmnopqrstuvwxyz"</span><span style="color: #0000FF;">,</span>
OT = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~",
<span style="color: #000000;">AZ</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"ABCDEFGHIJKLMNOPQRSTUVWXYZ"</span><span style="color: #0000FF;">,</span>
S4 = {az,AZ,O9,OT}
<span style="color: #000000;">O9</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"1234567890"</span><span style="color: #0000FF;">,</span>
 
<span style="color: #000000;">OT</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"!\"#$%&'()*+,-./:;&lt;=&gt;?@[]^_{|}~"</span>
function password(integer len, integer n, sequence exclude="Il1O05S2Z")
sequence res = {}
<span style="color: #008080;">function</span> <span style="color: #000000;">password</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">len</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">exclude</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"Il1O05S2Z"</span><span style="color: #0000FF;">)</span>
for i=1 to n do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{},</span>
sequence sel = shuffle({1,2,3,4}&sq_rand(repeat(4,len-4)))
<span style="color: #000000;">S4</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">filter</span><span style="color: #0000FF;">,{{</span><span style="color: #000000;">az</span><span style="color: #0000FF;">,</span><span style="color: #000000;">AZ</span><span style="color: #0000FF;">,</span><span style="color: #000000;">O9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">OT</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"out"</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">exclude</span><span style="color: #0000FF;">}})</span>
string pw = ""
<span style="color: #004080;">string</span> <span style="color: #000000;">pw</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #000000;">len</span><span style="color: #0000FF;">)</span>
for c=1 to length(sel) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
string S4c = S4[sel[c]]
<span style="color: #004080;">sequence</span> <span style="color: #000000;">sel</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">}&</span><span style="color: #7060A8;">sq_rand</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">len</span><span style="color: #0000FF;">-</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)))</span>
while 1 do
<span style="color: #008080;">for</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">len</span> <span style="color: #008080;">do</span>
integer ch = S4c[rand(length(S4c))]
<span style="color: #004080;">string</span> <span style="color: #000000;">S4c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">S4</span><span style="color: #0000FF;">[</span><span style="color: #000000;">sel</span><span style="color: #0000FF;">[</span><span style="color: #000000;">c</span><span style="color: #0000FF;">]]</span>
if not find(ch,exclude) then
<span style="color: #000000;">pw</span><span style="color: #0000FF;">[</span><span style="color: #000000;">c</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">S4c</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">S4c</span><span style="color: #0000FF;">))]</span>
pw &= ch
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
exit
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pw</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end while
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
res = append(res,pw)
end for
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
return res
end function
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">lenl</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">leng</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">numl</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">numb</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dlg</span>
 
integer len = prompt_number("Password length(4..99):",{4,99})
<span style="color: #008080;">function</span> <span style="color: #000000;">valuechanged_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*leng|numb*/</span><span style="color: #0000FF;">)</span>
integer n = prompt_number("Passwords required(1..99):",{1,99})
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">leng</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">),</span>
sequence passwords = password(len,n)
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">numb</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">)</span>
for i=1 to length(passwords) do
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">password</span><span style="color: #0000FF;">(</span><span style="color: #000000;">l</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
printf(1,"%s\n",{passwords[i]})
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"&"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"&&"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (on p2js??)</span>
end for</lang>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"SIZE"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">NULL</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupRefresh</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">lenl</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"length(4..99)"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">leng</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupText</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"SPIN=YES,SPINMIN=4,SPINMAX=99"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">numl</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"number(1..99)"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">numb</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupText</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"SPIN=YES,SPINMIN=1,SPINMAX=99"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"FONTFACE=Courier"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">({</span><span style="color: #000000;">leng</span><span style="color: #0000FF;">,</span><span style="color: #000000;">numb</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"VALUECHANGED_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"valuechanged_cb"</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">lenl</span><span style="color: #0000FF;">,</span><span style="color: #000000;">leng</span><span style="color: #0000FF;">,</span><span style="color: #000000;">numl</span><span style="color: #0000FF;">,</span><span style="color: #000000;">numb</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"GAP=10,NORMALIZESIZE=VERTICAL"</span><span style="color: #0000FF;">),</span>
<span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})},</span><span style="color: #008000;">"MARGIN=5x5"</span><span style="color: #0000FF;">),</span>
<span style="color: #008000;">`TITLE="Password Generator"`</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
With a length of 12 and generating 6 of them
<pre>
Password length(4..99):12
Passwords required(1..99):6
:EtF77s~%bok
C^Pb&NH8@?u6
Line 2,404 ⟶ 4,100:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">#!/usr/bin/pil
 
# Default seed
Line 2,467 ⟶ 4,163:
(rot '(*UppChars *Others *Digits *LowChars))) ) ) ) ) ) ) )
 
(bye)</langsyntaxhighlight>
Test:
<pre>$ genpw --help
Line 2,488 ⟶ 4,184:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function New-RandomPassword
{
Line 2,608 ⟶ 4,304:
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
New-RandomPassword -Length 12 -Count 4 -ExcludeSimilar
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,620 ⟶ 4,316:
</pre>
Make it Unix-like:
<syntaxhighlight lang="powershell">
<lang PowerShell>
Set-Alias -Name nrp -Value New-RandomPassword -Description "Generates one or more passwords"
 
nrp -l 12 -n 4 -x
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,635 ⟶ 4,331:
=={{header|Prolog}}==
{{works with|SWI-Prolog|7.6.4 or higher}}
<langsyntaxhighlight Prologlang="prolog">:- set_prolog_flag(double_quotes, chars).
:- initialization(main, main).
 
Line 2,692 ⟶ 4,388:
pword_char( upper, C ) :- member( C, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ).
pword_char( digits, C ) :- member( C, "0123456789" ).
pword_char( special, C ) :- member( C, "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" ).</langsyntaxhighlight>
{{out}}
Showing help
Line 2,728 ⟶ 4,424:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
 
Procedure.b CheckPW(pw.s)
Line 2,849 ⟶ 4,545:
~"Blabla blabla bla blablabla."
EndOfHelp:
EndDataSection</langsyntaxhighlight>
{{out}}
<pre>Length of the password (n>=4): 10
Line 2,870 ⟶ 4,566:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">import random
 
lowercase = 'abcdefghijklmnopqrstuvwxyz' # same as string.ascii_lowercase
Line 2,904 ⟶ 4,600:
for i in range(qty):
print(new_password(length, readable))
</syntaxhighlight>
</lang>
{{output}}
<pre>>>> password_generator(14, 4)
Line 2,918 ⟶ 4,614:
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang r>
passwords <- function(nl = 8, npw = 1, help = FALSE) {
if (help) return("gives npw passwords with nl characters each")
Line 2,943 ⟶ 4,639:
## Tj@T19L.q1;I*]
## 6M+{)xV?i|1UJ/
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 3,007 ⟶ 4,703:
 
(run (len) (cnt) (seed) (readable?))
</syntaxhighlight>
</lang>
'''Sample output:'''
<pre>
Line 3,022 ⟶ 4,718:
{{works with|Rakudo|2016.05}}
 
<syntaxhighlight lang="raku" perl6line>my @chars =
set('a' .. 'z'),
set('A' .. 'Z'),
Line 3,055 ⟶ 4,751:
{$*PROGRAM-NAME} --l=14 --c=5 --x=0O\\\"\\\'1l\\\|I
END
}</langsyntaxhighlight>
'''Sample output:'''
Using defaults:
Line 3,066 ⟶ 4,762:
9%-tYX]z?8-xA5</pre>
 
=={{header|Raku (=functional) }}===
<syntaxhighlight lang="raku" line>my @char-groups =
['a' .. 'z'],
['A' .. 'Z'],
['0' .. '9'],
< $ % & \ ` ~ ! * + , - . / : ; = ? @ ^ _ ~ [ ] ( ) { | } # ' " \< \> >.Array;
 
subset MinimumPasswordLength of Int where * >= 4;
<lang perl6>
subset MinimumPasswordLengthNumberOfPasswords of IntUInt where * >!= 40;
subset NumberOfPasswords of UInt where * != 0;
 
sub MAIN( NumberOfPasswords:D :c(:$count) = 1, MinimumPasswordLength :l(:$length) = 8, Str :x(:$exclude) = '' ) {
&USAGE() if 1 == (.comb ∖ $exclude.comb).elems for @char-groups;
{
.say for password-characters( char-groups($length, $exclude.comb ) )
.batchmap( $length*.split(' ') )
.map( *.pick: Inf ) # shuffle, so we don't get a predictable pattern
.map( *.join )
Line 3,081 ⟶ 4,781:
}
 
sub charpassword-groupscharacters( @$len, $exclude ) {
( (( char-groups($exclude) xx Inf ).map: *.pick).batch( 4)
{
state @char-groups =Z~
(( char-groups($exclude, $len) xx Inf ).map: *.pick).batch($len-4) )
['a' .. 'z'],
['A' .. 'Z'],
['0' .. '9'],
< $ % & \ ` ~ ! * + , - . / : ; = ? @ ^ _ ~ [ ] ( ) { | } # ' " \< \> >;
 
@char-groups
.map( * (-) @exclude )
.grep( *.so );
}
 
multi char-groups( $exclude ) { | @char-groups.map( * (-) $exclude.comb ) }
sub password-characters( @char-groups )
multi char-groups( $exclude, $max-weight ) { flat (char-groups($exclude)>>.keys.map: {$_ xx ^$max-weight .roll}) }
{
( |@char-groups xx Inf ).map: *.pick;
}
</lang>
 
sub USAGE() {
say qq:to/END/;
Specify a length: -l=10 (minimum 4)
Specify a count: -c=5 (minimum 1)
Specify characters to exclude: -x=xkcd (optional)
Password must have at least one of each: lowercase letter, uppercase letter, digit, punctuation.
END
}</syntaxhighlight>
'''Sample output:'''
 
Without parameters:
<pre>d[G2r4;i</pre>
Usage:
genpwd.raku [-c|--count=<NumberOfPasswords>] [-l|--length=<MinimumPasswordLength>] [-x|--exclude=<Str>]
</pre>
 
With passed parameters: -c=15 -l=12 -x=aeiou
<pre>Jk&>Az22</pre>x7)YbEZQ2xp2
CEpZ>#4'rO7d
With passed parameters: -l=4 -c=5 -x=abcdefghijklmnopqrstuvwxy
pn(5B;wb66DM
<pre>
KA;3T7=s+I5{
zH5^
LL<tB~L1~Y*q</pre>
4zT;
9/zJ
z6_U
!zC8
</pre>
 
=={{header|REXX}}==
Line 3,140 ⟶ 4,831:
:::* &nbsp; checking if the hexadecimal literal &nbsp; ('''yyy''') &nbsp; is valid
:::* &nbsp; checking (for instance) if all digits were excluded via the &nbsp; <b>'''xxx'''</b> &nbsp; and/or &nbsp; '''yyy''' &nbsp; option
<langsyntaxhighlight lang="rexx">/*REXX program generates a random password according to the Rosetta Code task's rules.*/
@L='abcdefghijklmnopqrstuvwxyz'; @U=@L; upper @U /*define lower-, uppercase Latin chars.*/
@#= 0123456789 /* " " string of base ten numerals.*/
Line 3,195 ⟶ 4,886:
║ The default is to use all the (normal) available characters. ║
║ yyy (same as XXX, except the chars are expressed as hexadecimal pairs).║
╚═════════════════════════════════════════════════════════════════════════════╝ */</langsyntaxhighlight>
'''output''' &nbsp; when using the inputs of: &nbsp; <tt> 10 &nbsp; 20 </tt>
<pre>
Line 3,221 ⟶ 4,912:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Password generator
 
Line 3,266 ⟶ 4,957:
end
fclose(fp)
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,273 ⟶ 4,964:
password = u8/Ah8%H
password = c4\Nc2_J
</pre>
 
=={{header|RPL}}==
{{works with|HP|48G}}
« "!" 34 CHR + "#$%&'()*+,-./:;<=>?@[]^_{|}~" + "" → chars pwd
« { 0 0 0 0 }
'''WHILE''' DUP2 ∑LIST 4 ≠ OR '''REPEAT'''
RAND 4 * CEIL
{ « RAND 25 * FLOOR 65 + CHR »
« RAND 25 * FLOOR 97 + CHR »
« RAND 10 * FLOOR →STR »
« chars RAND OVER SIZE * CEIL DUP SUB » }
OVER GET EVAL 'pwd' STO+
1 PUT
SWAP 1 - 0 MAX SWAP
'''END''' DROP2 pwd
» » '<span style="color:blue">→PWD</span>' STO ''<span style="color:grey">@ ( length → "password" )''</span>
« → length n
« '''IF''' length 4 < '''THEN'''
"Length must be at least 4" DOERR
'''ELSE'''
{ }
1 n '''FOR''' j
'''WHILE''' length <span style="color:blue">→PWD</span> DUP SIZE length > '''REPEAT''' DROP '''END'''
+
'''NEXT'''
'''END'''
» » '<span style="color:blue">PWDS</span>' STO <span style="color:grey">''@ ( length n → { "password1" .. "passwordn" } )''</span>
 
8 3 <span style="color:blue">PWDS</span>
{{out}}
<pre>
1: { "v7-c8d.B" "oVe1M$17" "R+I6vJ9j" }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight Rubylang="ruby">ARRS = [("a".."z").to_a,
("A".."Z").to_a,
("0".."9").to_a,
Line 3,292 ⟶ 5,017:
 
puts generate_pwd(8,3)
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">a$(1) = "0123456789"
a$(2) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
a$(3) = "abcdefghijklmnopqrstuvwxyz"
Line 3,334 ⟶ 5,059:
goto [main]
[exit] ' get outta here
end</langsyntaxhighlight>Output:
<pre>Generate 10 passwords with 7 characters
#1 69+;Jj8
Line 3,346 ⟶ 5,071:
#9 9P8Qx_P
#10 f0Qho:5</pre>
=={{header|Rust}}==
<syntaxhighlight lang="rust">
use rand::distributions::Alphanumeric;
use rand::prelude::IteratorRandom;
use rand::{thread_rng, Rng};
use std::iter;
use std::process;
use structopt::StructOpt;
const OTHER_VALUES: &str = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~";
 
// the core logic that creates our password
fn generate_password(length: u8) -> String {
// cache thread_rng for better performance
let mut rng = thread_rng();
// the Alphanumeric struct provides 3/4
// of the characters for passwords
// so we can sample from it
let mut base_password: Vec<char> = iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
.take(length as usize)
.collect();
let mut end_range = 10;
// if the user supplies a password length less than 10
// we need to adjust the random sample range
if length < end_range {
end_range = length;
}
// create a random count of how many other characters to add
let mut to_add = rng.gen_range(1, end_range as usize);
loop {
// create an iterator of required other characters
let special = OTHER_VALUES.chars().choose(&mut rng).unwrap();
to_add -= 1;
base_password[to_add] = special;
if to_add == 0 {
break;
}
}
base_password.iter().collect()
}
 
#[derive(StructOpt, Debug)]
#[structopt(name = "password-generator", about = "A simple password generator.")]
struct Opt {
// make it SECURE by default
// https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
/// The password length
#[structopt(default_value = "160")]
length: u8,
/// How many passwords to generate
#[structopt(default_value = "1")]
count: u8,
}
 
fn main() {
// instantiate the options and use them as
// arguments to our password generator
let opt = Opt::from_args();
const MINIMUM_LENGTH: u8 = 30;
if opt.length < MINIMUM_LENGTH {
eprintln!(
"Please provide a password length greater than or equal to {}",
MINIMUM_LENGTH
);
process::exit(1);
}
for index in 0..opt.count {
let password = generate_password(opt.length);
// do not print a newline after the last password
match index + 1 == opt.count {
true => print!("{}", password),
_ => println!("{}", password),
};
}
}
</syntaxhighlight>
{{out}}
<pre>
password-generator 30 5
 
%"/[:*|}zYNaC2C7IRsAXK8zDZR8JC
)fJGVcMqBLQkU5x2YOpo6Oyw0ezWHh
%/@&@2BBOQBLnH74lsqtj92eWZRQzc
|:%!r77MTosArmxe9J3LvKurcdOX3P
(=>#[!%|z84tH5edhGY48hoylopnIA
</pre>
 
=={{header|Scala}}==
Using SBT to run rather than a shell script or executable jar:
<langsyntaxhighlight lang="scala">object makepwd extends App {
 
def newPassword( salt:String = "", length:Int = 13, strong:Boolean = true ) = {
Line 3,416 ⟶ 5,227:
 
if( count > 1 ) println
}</langsyntaxhighlight>
{{output}}
> sbt "run --help"
Line 3,441 ⟶ 5,252:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func string: generate (in integer: length) is func
Line 3,496 ⟶ 5,307:
end if;
end if;
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,514 ⟶ 5,325:
Swift uses arc4random() to generate fast and high quality random numbers. However the usage of a user defined seed is not possible within arc4random(). To fulfill the requirements this code uses the C functions srand() and rand() that are integrated into the Swift file via an Bridging-Header.<br><br>
'''C file to generate random numbers'''
<langsyntaxhighlight Clang="c">#include <stdlib.h>
#include <time.h>
 
Line 3,528 ⟶ 5,339:
int getRand(const int upperBound){
return rand() % upperBound;
}</langsyntaxhighlight>
 
'''Bridging-Header to include C file into Swift'''
<langsyntaxhighlight Clang="c">int getRand(const int upperBound);
void initRandom(const unsigned int seed);</langsyntaxhighlight>
 
'''Swift file'''
<langsyntaxhighlight lang="swift">import Foundation
import GameplayKit // for use of inbuilt Fisher-Yates-Shuffle
 
Line 3,658 ⟶ 5,469:
for i in 1...count {
print("\(i).\t\(generatePassword(length:length,exclude:xclude))")
}</langsyntaxhighlight>
{{out}}
<pre>$ PasswordGenerator -h
Line 3,677 ⟶ 5,488:
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
Sub Main()
Line 3,875 ⟶ 5,686:
End If
z = temp
End Function</langsyntaxhighlight>
{{out}}
Function Gp :
Line 3,918 ⟶ 5,729:
 
3- Excl_Similar_Chars (Boolean) : True if you want the option of excluding visually similar characters.
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-ioutil}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "random" for Random
import "./ioutil" for FileUtil, File, Input
import "./fmt" for Fmt
import "os" for Process
 
var r = Random.new()
var rr = Random.new() // use a separate generator for shuffles
var lb = FileUtil.lineBreak
 
var lower = "abcdefghijklmnopqrstuvwxyz"
var upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var digit = "0123456789"
var other = """!"#$%&'()*+,-./:;<=>?@[]^_{|}~"""
 
var exclChars = [
"'I', 'l' and '1'",
"'O' and '0' ",
"'5' and 'S' ",
"'2' and 'Z' "
]
 
var shuffle = Fn.new { |s|
var sl = s.toList
rr.shuffle(sl)
return sl.join()
}
 
var generatePasswords = Fn.new { |pwdLen, pwdNum, toConsole, toFile|
var ll = lower.count
var ul = upper.count
var dl = digit.count
var ol = other.count
var tl = ll + ul + dl + ol
var fw = toFile ? File.create("pwds.txt") : null
if (toConsole) System.print("\nThe generated passwords are:")
for (i in 0...pwdNum) {
var pwd = lower[r.int(ll)] + upper[r.int(ul)] + digit[r.int(dl)] + other[r.int(ol)]
for (j in 0...pwdLen - 4) {
var k = r.int(tl)
pwd = pwd + ((k < ll) ? lower[k] :
(k < ll + ul) ? upper[k - ll] :
(k < tl - ol) ? digit[k - ll - ul] : other[tl - 1 - k])
}
for (i in 1..5) pwd = shuffle.call(pwd) // shuffle 5 times say
if (toConsole) Fmt.print(" $2d: $s", i + 1, pwd)
if (toFile) {
fw.writeBytes(pwd)
if (i < pwdNum - 1) fw.writeBytes(lb)
}
}
if (toFile) {
System.print("\nThe generated passwords have been written to the file pwds.txt")
fw.close()
}
}
 
var printHelp = Fn.new {
System.print("""
This program generates up to 99 passwords of between 5 and 20 characters in
length.
 
You will be prompted for the values of all parameters when the program is run
- there are no command line options to memorize.
 
The passwords can either be written to the console or to a file (pwds.txt),
or both.
 
The passwords must contain at least one each of the following character types:
lower-case letters : a -> z
upper-case letters : A -> Z
digits : 0 -> 9
other characters : !"#$%&'()*+,-./:;<=>?@[]^_{|}~
 
Optionally, a seed can be set for the random generator
(any non-zero number) otherwise the default seed will be used.
Even if the same seed is set, the passwords won't necessarily be exactly
the same on each run as additional random shuffles are always performed.
 
You can also specify that various sets of visually similar characters
will be excluded (or not) from the passwords, namely: Il1 O0 5S 2Z
 
Finally, the only command line options permitted are -h and -help which
will display this page and then exit.
 
Any other command line parameters will simply be ignored and the program
will be run normally.
 
""")
}
 
var args = Process.arguments
if (args.count == 1 && (args[0] == "-h" || args[0] == "-help")) {
printHelp.call()
return
}
 
System.print("Please enter the following and press return after each one")
 
var pwdLen = Input.integer(" Password length (5 to 20) : ", 5, 20)
var pwdNum = Input.integer(" Number to generate (1 to 99) : ", 1, 99)
 
var seed = Input.number (" Seed value (0 to use default) : ")
if (seed != 0) r = Random.new(seed)
 
System.print(" Exclude the following visually similar characters")
for (i in 0..3) {
var yn = Input.option(" %(exclChars[i]) y/n : ", "ynYN")
if (yn == "y" || yn == "Y") {
if (i == 0) {
upper = upper.replace("I", "")
lower = lower.replace("l", "")
digit = digit.replace("1", "")
} else if (i == 1) {
upper = upper.replace("O", "")
digit = digit.replace("0", "")
} else if (i == 2) {
upper = upper.replace("S", "")
digit = digit.replace("5", "")
} else if (i == 3) {
upper = upper.replace("Z", "")
digit = digit.replace("2", "")
}
}
}
 
var toConsole = Input.option(" Write to console y/n : ", "ynYN")
toConsole = toConsole == "y" || toConsole == "Y"
var toFile = true
if (toConsole) {
toFile = Input.option(" Write to file y/n : ", "ynYN")
toFile = toFile == "y" || toFile == "Y"
}
 
generatePasswords.call(pwdLen, pwdNum, toConsole, toFile)</syntaxhighlight>
 
{{out}}
Sample run:
<pre>
Please enter the following and press return after each one
Password length (5 to 20) : 8
Number to generate (1 to 99) : 10
Seed value (0 to use default) : 0
Exclude the following visually similar characters
'I', 'l' and '1' y/n : n
'O' and '0' y/n : n
'5' and 'S' y/n : n
'2' and 'Z' y/n : n
Write to console y/n : y
Write to file y/n : y
 
The generated passwords are:
1: 53oR=Y|#
2: LdT,[7x=
3: puQwj#0N
4: kY0:zL~m
5: 01BN!fqZ
6: +3Si33[}
7: !MV:9/wC
8: gcAY0m#_
9: h45R)A|c
10: SGrpk:86
 
The generated passwords have been written to the file pwds.txt
</pre>
 
=={{header|XPL0}}==
{{trans|Python}}
<syntaxhighlight lang "XPL0">string 0;
 
func In(C, Str);
char C, Str;
[while Str(0) do
if C = Str(0) then return true else Str:= Str+1;
return false;
];
 
func New_password(Length, Readable);
int Length, Readable, I, C;
char Password_chars(100), Punctuation, Visually_similar;
[if Length < 4 then
[Text(0, "Password length = "); IntOut(0, Length);
Text(0, " is too short, minimum length = 4.");
return "";
];
Punctuation:= "!^"#$%&\'()*+,-./:;<=>?@[]^^_{|}~";
Visually_similar:= "Il1O05S2Z";
for I:= 0 to Length-1 do
[case Ran(4) of
0: C:= Ran(26) + ^a;
1: C:= Ran(26) + ^A;
2: C:= Ran(10) + ^0;
3: C:= Punctuation(Ran(31))
other [];
Password_chars(I):= C;
if Readable and In(C, Visually_similar) then I:= I-1;
];
Password_chars(I):= 0;
return Password_chars;
];
 
proc Password_generator(Length, Qty, Readable);
int Length, Qty, Readable, I;
for I:= 0 to Qty-1 do
[Text(0, New_password(Length, Readable)); CrLf(0)];
 
[Password_generator(14, 4, true);
Password_generator( 8, 4, false);
]</syntaxhighlight>
{{out}}
<pre>
GojA9ep6=3|U,\
U9@p|f'WH7+&TM
8=E7xvm6J9Y([q
zrknig;8Pv+(Va
37s11T68
Ir)wY0P<
54d3o]Ga
95??s]"O
</pre>
 
=={{header|zkl}}==
Put the following code into a file (such as pwdg.zkl):
<langsyntaxhighlight lang="zkl">var pwdLen=10, pwds=1, xclude="";
 
argh:=Utils.Argh(
Line 3,943 ⟶ 5,979:
pwd:=T(g1,g2,g3,g4).pump(Data,rnd); // 1 from each of these into a Data
pwd.extend(fill()).shuffle().text.println();
}</langsyntaxhighlight>
This is a command line program so output can be redirected.
{{out}}
1,150

edits