Password generator: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 36:
=={{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.)
<langsyntaxhighlight lang="6502asm">LDY #0
LDX #20
LOOP:
Line 52:
DEX
BNE LOOP
BRK ;end program</langsyntaxhighlight>
 
{{out}}
Line 67:
Help is printed when no arguments are given.
 
<langsyntaxhighlight lang="asm"> cpu 8086
bits 16
;;; MS-DOS syscalls
Line 340:
lmask: resb 1 ; Mask for random number generation
rnddat: resb 4 ; RNG state
buffer: resb 257 ; Space to store password</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">BYTE FUNC GetNumParam(CHAR ARRAY text BYTE min,max)
BYTE res
 
Line 467:
UNTIL again=0
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Password_generator.png Screenshot from Atari 8-bit computer]
Line 495:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
with Ada.Strings.Fixed;
with Ada.Command_Line;
Line 686:
end loop;
 
end Mkpw;</langsyntaxhighlight>
{{out}}
<pre>$ ./mkpw count 8 length 22 safe
Line 699:
 
=={{header|Applesoft BASIC}}==
<langsyntaxhighlight Applesoftlang="applesoft">1 N=1
2 L=8
3 M$=CHR$(13)
Line 857:
900 Q = 1
910 VTAB 23
920 RETURN</langsyntaxhighlight>
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">lowercase: `a`..`z`
uppercase: `A`..`Z`
digits: `0`..`9`
Line 894:
loop 1..10 'x [
print generate to :integer first arg
]</langsyntaxhighlight>
 
{{out}}
Line 912:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f PASSWORD_GENERATOR.AWK [-v mask=x] [-v xt=x]
#
Line 1,010:
printf("example: %s -v mask=%s -v xt=%s\n",cmd,mask,xt)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,022:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 1,149:
return 0;
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,163:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 1,237:
return new string(password);
}
}</langsyntaxhighlight>
{{out}}
<pre>PASSGEN -l:12 -c:6
Line 1,248:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <algorithm>
Line 1,302:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 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 1,469:
Character[] filterCharsToExclude(Character[] chars, Character[] charsToExclude)
=> chars.filter((char) => ! charsToExclude.contains(char)).sequence();
</syntaxhighlight>
</lang>
 
 
Line 1,509:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(ns pwdgen.core
(:require [clojure.set :refer [difference]]
[clojure.tools.cli :refer [parse-opts]])
Line 1,547:
(if (:help options) (println summary)
(dotimes [n (:count options)]
(println (apply str (generate-password options)))))))</langsyntaxhighlight>
 
{{out}}
Line 1,571:
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.
 
<langsyntaxhighlight lang="gwbasic">1 rem password generator
2 rem rosetta code
10 g$(1)="abcdefghijklmnopqrstuvwxyz"
Line 1,633:
610 print "Press any key to begin."
615 get k$:if k$="" then 615
620 return</langsyntaxhighlight>
 
{{out}}
Line 1,689:
 
=={{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 1,736:
(loop for x from 1 to count do
(print (generate-password len human-readable)))))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,749:
 
=={{header|Crystal}}==
<langsyntaxhighlight Crystallang="crystal">require "random/secure"
 
special_chars = true
Line 1,820:
break if count <= 0
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 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 1,905:
end
 
Password.generator</langsyntaxhighlight>
 
{{out}}
Line 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 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 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 2,019:
[ parse-args gen-pwds ] [ 2drop usage print ] recover ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 2,044:
 
=={{header|FreeBASIC}}==
{{trans|Run BASIC}}<langsyntaxhighlight lang="freebasic">Dim As String charS(4)
charS(1) = "0123456789"
charS(2) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Line 2,081:
Wend
Sleep
</syntaxhighlight>
</lang>
{{out}}
<pre>------ Password Generator ------
Line 2,096:
=={{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 2,165:
Print sPassword 'Print the password list
 
End</langsyntaxhighlight>
Output:
<pre>
Line 2,185:
 
=={{header|Go}}==
<syntaxhighlight lang="go">
<lang Go>
package main
 
Line 2,278:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,296:
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 2,315:
x <- uniform lst
xs <- shuffle (delete x lst)
return (x : xs)</langsyntaxhighlight>
 
For example:
Line 2,327:
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 2,353:
, "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" ]
 
visualySimilar = ["l","IOSZ","012","!|.,"]</langsyntaxhighlight>
 
{{Out}}
Line 2,406:
Implementation:
 
<langsyntaxhighlight Jlang="j">thru=: <. + i.@(+*)@-~
chr=: a.&i.
 
Line 2,428:
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 2,446:
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 2,515:
return sb.toString();
}
}</langsyntaxhighlight>
 
<pre>7V;m
Line 2,529:
 
=={{header|JavaScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">String.prototype.shuffle = function() {
return this.split('').sort(() => Math.random() - .5).join('');
}
Line 2,582:
console.log( createPwd( {len: 20, num: 2}) );
console.log( createPwd( {len: 20, num: 2, noSims: false}) );
</syntaxhighlight>
</lang>
{{out}}<pre>
> Q^g"7
Line 2,593:
{{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 2,621:
end
 
passgen(stdout, 10, 12; seed = 1)</langsyntaxhighlight>
 
{{out}}
Line 2,638:
 
=={{header|Kotlin}}==
<langsyntaxhighlight Groovylang="groovy">// version 1.1.4-3
 
import java.util.Random
Line 2,828:
generatePasswords(pwdLen!!, pwdNum!!, toConsole, toFile!!)
}</langsyntaxhighlight>
 
Sample input and output:
Line 2,860:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function randPW (length)
local index, pw, rnd = 0, ""
local chars = {
Line 2,889:
os.exit()
end
for i = 1, arg[2] do print(randPW(tonumber(arg[1]))) end</langsyntaxhighlight>
Command line session:
<pre>>lua pwgen.lua
Line 2,908:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="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 2,938:
]</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import os, parseopt, random, sequtils, strformat, strutils
 
const Symbols = toSeq("!\"#$%&'()*+,-./:;<=>?@[]^_{|}~")
Line 3,039:
# Display the passwords.
for pw in passGen(passLength, count, seed, excludeSimilars):
echo pw</langsyntaxhighlight>
 
{{out}}
Line 3,052:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let lower = "abcdefghijklmnopqrstuvwxyz"
let upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let digit = "0123456789"
Line 3,108:
for i = 1 to !num do
print_endline (mk_pwd !len !readable)
done</langsyntaxhighlight>
 
{{out}}
Line 3,130:
=={{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 3,227:
¦ 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 3,252:
 
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 3,266:
}
 
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 3,286:
 
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">
<lang PASCAL>
program passwords (input,output);
 
Line 3,463:
end.
 
</syntaxhighlight>
</lang>
Useage for the output example: passwords --about -h --length=12 --number 12 --exclude
 
Line 3,498:
=={{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>.
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 3,547:
[--help]
END
}</langsyntaxhighlight>
{{out}}
<pre>sc3O~3e0
Line 3,557:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--with javascript_semantics -- not quite yet:</span>
<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>
Line 3,614:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
{{out}}
With a length of 12 and generating 6 of them
Line 3,627:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">#!/usr/bin/pil
 
# Default seed
Line 3,690:
(rot '(*UppChars *Others *Digits *LowChars))) ) ) ) ) ) ) )
 
(bye)</langsyntaxhighlight>
Test:
<pre>$ genpw --help
Line 3,711:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function New-RandomPassword
{
Line 3,831:
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
New-RandomPassword -Length 12 -Count 4 -ExcludeSimilar
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,843:
</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 3,858:
=={{header|Prolog}}==
{{works with|SWI-Prolog|7.6.4 or higher}}
<langsyntaxhighlight Prologlang="prolog">:- set_prolog_flag(double_quotes, chars).
:- initialization(main, main).
 
Line 3,915:
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 3,951:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
 
Procedure.b CheckPW(pw.s)
Line 4,072:
~"Blabla blabla bla blablabla."
EndOfHelp:
EndDataSection</langsyntaxhighlight>
{{out}}
<pre>Length of the password (n>=4): 10
Line 4,093:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">import random
 
lowercase = 'abcdefghijklmnopqrstuvwxyz' # same as string.ascii_lowercase
Line 4,127:
for i in range(qty):
print(new_password(length, readable))
</syntaxhighlight>
</lang>
{{output}}
<pre>>>> password_generator(14, 4)
Line 4,141:
 
=={{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 4,166:
## Tj@T19L.q1;I*]
## 6M+{)xV?i|1UJ/
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 4,230:
 
(run (len) (cnt) (seed) (readable?))
</syntaxhighlight>
</lang>
'''Sample output:'''
<pre>
Line 4,245:
{{works with|Rakudo|2016.05}}
 
<syntaxhighlight lang="raku" perl6line>my @chars =
set('a' .. 'z'),
set('A' .. 'Z'),
Line 4,278:
{$*PROGRAM-NAME} --l=14 --c=5 --x=0O\\\"\\\'1l\\\|I
END
}</langsyntaxhighlight>
'''Sample output:'''
Using defaults:
Line 4,290:
 
===functional===
<syntaxhighlight lang="raku" perl6line>my @char-groups =
['a' .. 'z'],
['A' .. 'Z'],
Line 4,324:
Password must have at least one of each: lowercase letter, uppercase letter, digit, punctuation.
END
}</langsyntaxhighlight>
'''Sample output:'''
 
Line 4,358:
:::* &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 4,413:
║ 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 4,439:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Password generator
 
Line 4,484:
end
fclose(fp)
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,494:
 
=={{header|Ruby}}==
<langsyntaxhighlight Rubylang="ruby">ARRS = [("a".."z").to_a,
("A".."Z").to_a,
("0".."9").to_a,
Line 4,510:
 
puts generate_pwd(8,3)
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">a$(1) = "0123456789"
a$(2) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
a$(3) = "abcdefghijklmnopqrstuvwxyz"
Line 4,552:
goto [main]
[exit] ' get outta here
end</langsyntaxhighlight>Output:
<pre>Generate 10 passwords with 7 characters
#1 69+;Jj8
Line 4,565:
#10 f0Qho:5</pre>
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
use rand::distributions::Alphanumeric;
use rand::prelude::IteratorRandom;
Line 4,639:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,653:
=={{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 4,720:
 
if( count > 1 ) println
}</langsyntaxhighlight>
{{output}}
> sbt "run --help"
Line 4,745:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func string: generate (in integer: length) is func
Line 4,800:
end if;
end if;
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,818:
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 4,832:
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 4,962:
for i in 1...count {
print("\(i).\t\(generatePassword(length:length,exclude:xclude))")
}</langsyntaxhighlight>
{{out}}
<pre>$ PasswordGenerator -h
Line 4,981:
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
Sub Main()
Line 5,179:
End If
z = temp
End Function</langsyntaxhighlight>
{{out}}
Function Gp :
Line 5,228:
{{libheader|Wren-ioutil}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="python">import "random" for Random
import "/ioutil" for FileUtil, File, Input
import "/fmt" for Fmt
Line 5,362:
}
 
generatePasswords.call(pwdLen, pwdNum, toConsole, toFile)</langsyntaxhighlight>
 
{{out}}
Line 5,396:
=={{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 5,417:
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}}
10,333

edits