Tell me more ×
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.

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
4  
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
1  
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
14  
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
show 6 more comments

61 Answers

1 2 3

BASH*

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
1  
@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
1  
Try pwgen -1s. – Mechanical snail Aug 5 '11 at 2:24
show 6 more comments
$s=implode('',array_rand(array_flip(array_merge(range('a','z'),range('A','Z'),range('0','9'))),8));

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:

while(strlen($s.=array_rand(array_flip(array_merge(range('a','z'),range('A','Z'),range('0','9')))))<8){}
share|improve this answer
show 1 more comment

C#

Guid.NewGuid();

This should work :)

Ok, fitting in the rules:

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

Nice hint David

share|improve this answer
1  
+1 for... well... +1, anyways. ;) – muntoo Mar 10 '11 at 0:13
1  
No mixed case, no letters above f. – J B Mar 10 '11 at 7:45
4  
-1 (if I had enough rep to do so). Guid.NewGuid() is not random enough to be used for anything security related! stackoverflow.com/questions/730268/… – Jørn Schou-Rode Mar 10 '11 at 8:46
3  
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
show 2 more comments

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
2  
+1 for the import trick, even if the the OP asked for PHP. – Juan Mar 9 '11 at 21:59
1  
@JB: Aren't all code challanges language agnostic? – nyuszika7h Apr 27 '11 at 12:05
show 6 more comments
$pass = substr(md5(rand()), 0, 8);
share|improve this answer
3  
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
4  
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
show 1 more comment

Python

"".join(__import__('random').sample(__import__('string').printable[:62],8))
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));

And:

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

Easy.

function securityismymiddlename() {return 'password';}
share|improve this answer
1  
Which language is it? – user unknown May 5 '11 at 3:51
3  
It's written in a special security-enhanced version of JavaScript. – Nick Pierpoint May 5 '11 at 23:27
1  
that's valid php too. – zzzzBov May 14 '11 at 20:14
show 1 more comment

J, 29 characters

a.{~(+48 55 61{~9 35&I.)?8$62
share|improve this answer
1  
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
1  
8 characters shorter: a.{~(+48 55 61{~9 35&I.)?8$62 – ephemient Nov 2 '11 at 0:01
show 2 more comments

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 | 
    % { 
        [char](
                ( 
                    ('0','9'),
                    ('A','Z'),
                    ('a','z')
                 ) | 
                 % { 
                    [char]$_[0]..[char]$_[1] 
                   } 
             )[(random)%62] 
          }
   ) -join ""
share|improve this answer

Javascript

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

alert(Math.random().toString(36).substr(2));

Try it out here: http://jsfiddle.net/ReYjF/

share|improve this answer

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

(0..7).map{[*?a..?z,*?A..?Z,*?0..?9].sample}.join

A version that never uses the same char twice:

[*?a..?z,*?A..?Z,*?0..?9].sample(8).join

edit: shaved off two more chars.

(0..7).map{(?0..?z).grep(/[\w\d]/).sample}.join
share|improve this answer
3  
.join can be shortened to *''. – Lars Haugseth May 5 '11 at 12:27

I'll give it a shot

for($c=array_merge(range(0,9),range('A','Z'),range('a','z'));strlen($p.=$c[array_rand($c)])<8;);

edit: and here's another one:

substr(preg_replace('/[^[:alnum:]]/','',crypt(uniqid(),'lr')),-8);
share|improve this answer

PHP:

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(time())), 0, 8);
share|improve this answer

BASH*

Another one for shell:

date | md5sum | base64 | cut -c-8

* Just unix shell commands actually

share|improve this answer
1  
TIL about bas64 utility. – st0le May 6 '11 at 6:10
show 1 more comment

Groovy

(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
show 1 more comment

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
show 1 more comment
echo implode('', array_map(function () { return substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ0123456789', mt_rand(0, 64), 1); }, range(1, 8)));
share|improve this answer
show 1 more comment

Javascript:

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
for($i=0;$i<8;$i++){$p.=array_rand(array_flip(array(chr(rand(48,57)),chr(rand(65,90)),chr(rand(97,122)))));}

echo $p;
share|improve this answer
show 1 more comment

C#

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

output:
"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");

output:
Thu81Mar

share|improve this answer

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
1  
-30 chars: perl -e'print+(0..9,A..Z,a..z)[rand 62]for 1..8' – ephemient Nov 2 '11 at 0:26

C

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() {
    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);
}

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'.

EDIT:

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

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);

    std::cin.ignore();

    return(0);
}

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
2  
Nice thinking about the ternary operator =) – Can Berk Güder Mar 10 '11 at 2:25

Python (72 67 54 chars)

`__import__('random').random()`.encode("base64")[3:11]
share|improve this answer
show 5 more comments

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

Here's another in Python, pulling one from gnibbler above...

__import__('base64').b64encode(str(__import__('random').getrandbits(256)))[:8]

I would like to be able to get a random 8 character slice of the string generated from b64encode(). Anyone know how to do that in one line?

You could use urlsafe_b64encode() if you want to avoid + and / characters...

share|improve this answer

C#

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
show 2 more comments

C#

One-liner:

Func<string> newPassword = () => new string("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".Zip(Enumerable.Range(0, 62), Tuple.Create).Join(Enumerable.Range(0, 8).Select(r => Guid.NewGuid().ToString().Where(char.IsNumber).Select(Convert.ToInt32).Sum() % 62), o => o.Item2, i => i, (l, r) => l.Item1).ToArray());

Example app:

using System;
using System.Linq;

namespace ConsoleApplication36
{
    class Program
    {
        static void Main()
        {
            Func<string> newPassword = () => new string(
                "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
                .Zip(Enumerable.Range(0, 62), Tuple.Create)
                .Join(
                    Enumerable.Range(0, 8).Select(r => Guid.NewGuid().ToString().Where(char.IsNumber).Select(Convert.ToInt32).Sum() % 62),
                    o => o.Item2,
                    i => i,
                    (l, r) => l.Item1)
                .ToArray());

            Console.WriteLine(string.Join("\n", Enumerable.Range(0, 20).Select(c => newPassword())));
            Console.ReadKey();
        }
    }
}
share|improve this answer
1 2 3

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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