Sign up ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Is there a way of writing a password generator in only one line?

The password should consist of 8 random chars out of a-z, A-Z and 0-9.

It should also return a different password every-time. Also, you can not use characters that can combine two lines of code into one, like ; (if your program language just works by having a series of commands on the same line without a special separator, that is okay.)

Example: This is one attempt I made in PHP!

echo substr(str_shuffle(implode('', array_merge(range(0,9), range('a','z'), 
    range('A','Z')))), 0, 8);
share|improve this question

closed as off-topic by undergroundmonorail, nyuszika7h, ProgramFOX, professorfish, Doorknob Jun 18 '14 at 12:10

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions without an objective primary winning criterion are off-topic, as they make it impossible to indisputably decide which entry should win." – undergroundmonorail, ProgramFOX, professorfish, Doorknob
If this question can be reworded to fit the rules in the help center, please edit the question.

Your attempt also generates really bad passwords. By not allowing repetition you reduce the entropy of an 8-character password over that alphabet from 47.6 bits to 31.7 bits. – Peter Taylor Mar 9 '11 at 10:19
Which version of PHP? The manual indicates that some versions have a function str_shuffle to shuffle a string and return the shuffled string. – Peter Taylor Mar 9 '11 at 20:23
In the spirit of the site, I'm broadening this to all languages, though PHP solutions are welcome – Jeff Atwood Mar 9 '11 at 23:34
Python (10 characters): 'aaaaaaaa' – Mechanical snail Aug 5 '11 at 2:49
For the record: Any passwords generated within the limitations of this challenge (8 characters, alphanumeric) are still fairly weak by today's standards. I doubt you'll find any security professional recommending less than 12, and even that is pushing it anymore. – Iszi Dec 10 '13 at 1:23

69 Answers 69



This should work :)

Ok, fitting in the rules:

Guid.NewGuid().ToString("N").Substring(0, 8);

Nice hint David

share|improve this answer
+1 for... well... +1, anyways. ;) – Mateen Ulhaq Mar 10 '11 at 0:13
doesn't ToString take a format parameter. "N" i think strips the dashes. Though i'm not sure. – David Murdoch Mar 10 '11 at 1:36
No mixed case, no letters above f. – J B Mar 10 '11 at 7:45
-1 (if I had enough rep to do so). Guid.NewGuid() is not random enough to be used for anything security related!… – Jørn Schou-Rode Mar 10 '11 at 8:46
Jørn: Most answers here use a PRNG which is even easier to reverse-engineer, so you'd have to downvote nearly everyone. What's more, I haven't found any information to which Windows version that applies and whether .NET uses the exact same algorithm. Which would be helpful in deciding whether your statement is valid here. – Joey Apr 16 '11 at 10:01


Simple and cute:

</dev/urandom tr -dc [:alnum:] | head -c8  

for all locales, or

</dev/urandom tr -dc a-zA-Z0-9 | head -c8  

for ASCII only.

* Just unix shell commands actually

share|improve this answer
You can get rid of a few of the spaces: tr -dc a-zA-Z0-9</dev/urandom|head -c8. The tr on Mac OS X doesn't seem to like getting input piped from /dev/urandom; it complains about invalid bytes. Works fine on Linux, though. – Brian Campbell Mar 18 '11 at 22:50
@Brian: Thanks :) but I think it's clearer with the spaces (since it is "one-liner" rather than "code golf"). – Eelvex Mar 19 '11 at 0:33
Oh, sorry. Missed the fact that this wasn't code-golf. Anyhow, I had come up with the same solution, and decided to check to see if anyone else had already done it, which you had. – Brian Campbell Mar 19 '11 at 2:50
@Eelvex: Actually, it's the shell (bash or sh) glob-expanding characters within the brackets (namely, :, a, l, n, u, and m). I have a directory named n in my home directory, so that's what [:alnum:] expanded to for me. – Joey Adams Mar 20 '11 at 16:48
Try pwgen -1s. – Mechanical snail Aug 5 '11 at 2:24

Python (93 92 91 87 82 chars)

z=__import__;''.join(z('random').choice(z("string").printable[:62]) for x in'.'*8)    
share|improve this answer
It seems the OP asks for PHP. – J B Mar 9 '11 at 21:42
+1 for the import trick, even if the the OP asked for PHP. – Juan Mar 9 '11 at 21:59
@JB: Aren't all code challanges language agnostic? – nyuszika7h Apr 27 '11 at 12:05
@Nyuszika7H: my comment was written at a time this question was neither a code-challenge nor language-agnostic. – J B Apr 27 '11 at 18:00
You can save one character by using python's native random choice function. I'll edit it in – jsvk Oct 22 '12 at 10:11



It has the same issue, that it won't repeat characters. But at least it works :P

Now this version does as asked, and repeats characters:

share|improve this answer
Very creative. +1 – Steve Robbins Nov 2 '11 at 0:13
$pass = substr(md5(rand()), 0, 8);
share|improve this answer
Love the idea, but I'm afraid md5 only returns hex digits. base64 would almost do the trick, if you could weed out whatever 2 remaining characters it uses. – J B Mar 9 '11 at 23:46
I think the two extra characters are \r and \n, so you could probably do substr(str_replace(array("\r","\n"),"",base64_encode(md5(rand()))), 0, 8) – mobiusnz Mar 12 '11 at 21:50
Interesting idea! – powtac May 9 '11 at 11:52
PHP follows section 6.8 - the extra characters are '+' and '/', along with '=' as a padding character. – Iiridayn Sep 14 '13 at 2:22


function securityismymiddlename() {return 'password';}
share|improve this answer
Which language is it? – user unknown May 5 '11 at 3:51
@user unknown: Probably JavaScript. But it's so simple it's probably valid in others. – Lowjacker May 5 '11 at 21:19
It's written in a special security-enhanced version of JavaScript. – Nick Pierpoint May 5 '11 at 23:27
that's valid php too. – zzzzBov May 14 '11 at 20:14
As random as this – moose Jul 23 '13 at 6:47


share|improve this answer

JavaScript. I've made two, although I allow all 62 characters between A and ~.

(function(n){return eval("["+Array(n).join("String.fromCharCode(65+~~(Math.random()*61)),")+",'']").join("");}(8));


(function(n,p){while(n--){p+=String.fromCharCode(65+~~(Math.random()*61))}return p;}(8,""));
share|improve this answer

J, 29 characters

a.{~(+48 55 61{~9 35&I.)?8$62
share|improve this answer
beat me to it. ?(62"0)^:<8 can be rewritten as ?8$62. Also, you can shave off a character by not using {~ the second time: a.{~(?8$62){(48+i.10),(65&+,97&+)i.26 – cobbal Mar 9 '11 at 23:51
@cobbal Indeed. Thanks! – J B Mar 9 '11 at 23:53
8 characters shorter: a.{~(+48 55 61{~9 35&I.)?8$62 – ephemient Nov 2 '11 at 0:01
@ephemient very cool. Thanks! – J B Nov 2 '11 at 14:35

Windows Powershell

 (1..8 | % { [char](( ('0','9'),('A','Z'),('a','z')) | % { [char]$_[0]..[char]$_[1] } )[(random)%62] }) -join ""

94 Characters, technically one line of code.

With formatting:

 (1..8 | 
    % { 
                 ) | 
                 % { 
   ) -join ""
share|improve this answer


44 chars

This one is fairly short but does not include capital letters. I posted it because I just like it the way it is. ;P


Try it out here:

share|improve this answer
This doesn't output a password of length 8. You could do alert(Math.random().toString(36).slice(-8)) – tristin Dec 10 '13 at 17:17

Yet another one in Ruby - only core lib and the shortest!


A version that never uses the same char twice:


edit: shaved off two more chars.

share|improve this answer
.join can be shortened to *''. – Lars Haugseth May 5 '11 at 12:27

I'll give it a shot


edit: and here's another one:

share|improve this answer


DateTime.Now.ToString("r").Replace(",", "").Replace(" ", "").Replace(":", "").Substring(0,8);

"r" = Thu, 10 Mar 2011 00:48:06 GMT
password: Thu10Mar

That's obviously only useful once a day. More random:

DateTime.Now.ToString("ddd") + DateTime.Now.Ticks.ToString().Substring(DateTime.Now.Ticks.ToString().Length -2) + DateTime.Now.ToString("MMM");


share|improve this answer


Another one for shell:

date | md5sum | base64 | cut -c-8

* Just unix shell commands actually

share|improve this answer
similar: cat /proc/sys/kernel/random/uuid | base64 | cut -c-8 – user unknown May 5 '11 at 3:56
TIL about bas64 utility. – st0le May 6 '11 at 6:10


(0..7).collect{(('a'..'z')+('A'..'Z')+(0..9))[new Random().nextInt(62)]}.join()

I knew Ruby and Groovy had much in common but the likeness of the solutions are even closer than I would have thought.

share|improve this answer
plus1 for Groovy. – david Nov 5 '12 at 12:20

PHP, Follows rules perfectly

echo substr(str_replace(array('/','+','='),'',base64_encode(md5(time()))), 0, 8); 
share|improve this answer

PHP, Here's another PHP solution that follows the rules exactly, this one might be 'more random' too.

<? echo substr(str_shuffle(str_repeat('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',8)), 0, 8);?>
share|improve this answer
range('a', 'z') could be used instead of 'abcdefghijklmnopqrstuvwxyz' – powtac Sep 14 '12 at 10:51
echo implode('', array_map(function () { return substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ0123456789', mt_rand(0, 64), 1); }, range(1, 8)));
share|improve this answer
(as an added bonus, it allows to specify any alphabet desired). – Einar Lielmanis Mar 10 '11 at 12:23


Here's one that writes out in one line in PHP. But it can only output passwords with lowercase alphabet characters and numbers.

echo "Here's your password: " . substr(md5(strval(rand())), 0, 8);
share|improve this answer


Disclaimer: This is not a serious answer. And I did not invent it, either. But it was too tempting to add it here.

In three steps:

  1. Write the single-line command:

  2. Put a fresh student in front of open editor;

  3. Ask him to quit.

share|improve this answer
LOL! The first time I used Vi I found C-z :D – core1024 Jun 12 '14 at 17:47
Quitting is the only thing I know how to do in that abomination :) – aditsu Jun 12 '14 at 21:20


string password = new String(Enumerable.Range('0', 'z'-'A'+1).Select(i => (char)i).Where(i => char.IsLetterOrDigit(i)).OrderBy(i => Guid.NewGuid()).Take(8).ToArray());
share|improve this answer
Could also do this with "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".Split but I hate that – Jon Galloway Mar 10 '11 at 0:19
Ah, just noticed the comments saying that a better solution should allow repetition. Not sure how best to do that. – Jon Galloway Mar 10 '11 at 0:25


alert((function(i) {return ((i < 7) ? arguments.callee(++i) : '') + (Math.round(Math.random() * 1) == 1 ? (Math.round(Math.random() * 1) == 1 ? String.fromCharCode(65 + Math.round(Math.random() * 25.5)) : String.fromCharCode(97 + Math.round(Math.random() * 25.5))) : String.fromCharCode(48 + Math.round(Math.random() * 9.5))) + ''}).call(this, 0))

Because I like recursion and Javascript and I don't consider a loop construct to be "one" line.

I suspect it is more likely to generate numbers than letters though.... Fortunately, it restricts itself to lowercase and uppercase letters and numbers only.

share|improve this answer

echo $p;
share|improve this answer
Which language is it? Or shall we not name it? :) – user unknown May 5 '11 at 3:48

Perl, from command-line:

perl -e '@r=(a..z,A..Z,0..9);$p.=$r[int(rand(@r))],$i++while($i<8);print"$p\n"'
share|improve this answer
-30 chars: perl -e'print+(0..9,A..Z,a..z)[rand 62]for 1..8' – ephemient Nov 2 '11 at 0:26


123 bytes, excluding #include lines.

int r,i;main(){srand(time(0));while(++i<9){r=rand()%62;if(r>35)r+=61;else if(r>9)r+=55;else r+=48;putchar(r);}putchar(10);}

Properly formatted:

#include <stdio.h>
#include <stdlib.h>

int r, i;

main() {

    while (++i < 9) {
        r = rand() % 62;

        if (r > 35)
            r += 61;
        else if (r > 9)
            r += 55;
            r += 48;



Of course, you would want to use random() instead of rand() in a real application. I'm just shaving bytes.

Also, since 62 is not a power of 2, using mod slightly favors '0' and '1'.


Using the ternary operator (after muntoo's answer), 101 bytes:

int r,i;main(){srand(time(0));while(++i<9)putchar((r=rand()%62)<10?r+48:r<36?r+55:r+61);putchar(10);}
share|improve this answer



Very short but not entirely correct because it only outputs /a-z0-9/

The next one returns a base64 encoded password with the / and + removed so that it fulfills the requirements

[ {rand(256)}.pack('C*')].pack('m*').tr("/+","")[0..7]

Ugly, I know.

share|improve this answer

C++, 77

for(char i=0,r;i<8;i++)std::cout<<char((r=rand()%62)<10?r+48:r<36?r+55:r+61);

Full program:

#include <iostream>
#include <time.h>

int main(int argc, char* argv[])
    for(char i=0,r;i<8;i++)std::cout<<char((r=rand()%62)<10?r+48:r<36?r+55:r+61);



For some reason, this doesn't run as expected:

for(char i=0,r;i<8;i++,srand(time(0)))std::cout<<(char)(((r=rand()%62)<10)?r+48:r<36?r+55:r+61);
share|improve this answer
Nice thinking about the ternary operator =) – Can Berk Güder Mar 10 '11 at 2:25

Python (72 67 54 chars)

share|improve this answer
Nice one. Maybe you can use str.encode('base64') instead of importing the module – gnibbler Oct 22 '12 at 11:21
and full circle to os.urandom :) __import__('os').urandom(9).encode("base64")[:8] – gnibbler Oct 22 '12 at 11:29
nice, I'd completely forgotten about str.encode(...), and today I learned about `...`. The solution you suggested here seems to return '/' characters as part of the mix sometimes, though, e.g. 7W4/sNqV – jsvk Oct 22 '12 at 12:27
The urandom solution, I mean – jsvk Oct 22 '12 at 22:27
Yes you are correct. the base64 for just numerics doesn't require the full set of base64 characters. – gnibbler Oct 22 '12 at 23:27

Considering that security should be the upmost priority, and someone may stumble across this thread and actually try to use the code here (the horror), I feel this answer is appropriate:

Use A Library!!!

In PHP, You could use the GenPhrase Library:

PHP (37 characters)

(new GenPhrase\Password)->generate();

That will generate a word list (longer than 8 characters) with a minimum of 50 bits of entropy...

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.