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
3  
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
@Peter Taylor, I'm searching for a better solution, if there is one ;) – powtac Mar 9 '11 at 10:48
@Peter Taylor you are right, its not the very best algorithm! – powtac Mar 9 '11 at 12:28
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 4 more comments

58 Answers

1 2

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
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
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 3 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
Very creative. +1 – Steve Robbins Nov 2 '11 at 0:13

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

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
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
@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
show 3 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
Interesting idea! – powtac May 9 '11 at 11:52

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
@user unknown: Probably JavaScript. But it's so simple it's probably valid in others. – Lowjacker May 5 '11 at 21:19
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

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

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
@cobbal Indeed. Thanks! – J B Mar 9 '11 at 23:53
1  
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

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
similar: cat /proc/sys/kernel/random/uuid | base64 | cut -c-8 – user unknown May 5 '11 at 3:56
1  
TIL about bas64 utility. – st0le May 6 '11 at 6:10

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

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
Which language is it? Or shall we not name it? :) – user unknown May 5 '11 at 3:48

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

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

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

Ruby

require 'securerandom';SecureRandom.urlsafe_base64.delete('-_')[0,8]
share|improve this answer
require 'securerandom';SecureRandom.urlsafe_base64.delete('-_')[0,8] - is irb1.8 not well suited/too old? Do I need additional libraries? – user unknown May 5 '11 at 3:41
It 's in my Ruby 1.9.2 standard lib. ActiveSupport has a module with the same name; it claims to have the same interface as the Ruby 1.9 module, but looking at the methods, it doesn't (anymore). – steenslag May 5 '11 at 22:20
1 2

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.