Gerry
Gerry

Reputation: 207

Generate all combinations from list of characters

I am busy implementing a lab for pen testers to create MD5 hashes from 4 letter words. I need the words to have a combination of lower and uppercase letters as well as numeric and special characters, but I just do not seem to find out how to combine any given characters in all orders. So currently I have this:

my $str = 'aaaa';
print $str++, $/ while $str le 'dddd';

Which will do:

aaaa
aaab
aaac
aaad
...
...
dddd

There is no way however how I can make it do:

Aaaa
AAaa
aAaa
...
dddD

Not even to mention adding numbers and special characters. What I really wanted to do was to make the characters to create words based on a given list. So if I feel I want to use abeDod@# it should create all combinations from those characters.

Edit to clarify.

Let's say I give the characters aBc# I need it to give it a a count to say it must have maximum of 4 letters per word and with combination of all the given characters, like:

aBc#
Bac#
caB#
#Bca
...

I hope that clarifies the question.

Upvotes: 1

Views: 454

Answers (1)

zdim
zdim

Reputation: 66883

Use a list of integers that are ASCII codes for the characters you accept, to sample from it using your favorite (pseudo-)random number generator. Then convert each to its character using chr and concatenate them.

Like

perl -wE'$rw .= chr( 32+(int rand 126-32) ) for 1..4; say $rw'

Notes

  • I use a one-liner merely for easy copy-paste testing. Write this nicely in a script, please

  • I use the sketchy rand, good for shuffling things a bit. Replace with a better one if needed

  • Glueing four (pseudo-)random numbers does not build a good distribution; even as each letter on its own does, the whole thing does not. But the four should satisfy most needs.

    If not, I think that you'd need to produce a far longer list (range of allowed chars repeated four times perhaps) and randomize it, then draw four-letter subsequences. A lot more work

  • I need to tap dance a little to produce (random-ish) integers from 32 to 126 using rand, since it takes only the end of range. Also, this takes all of them from that range, likely not what you want; so specify subranges, or specific lists that you want to draw from

Upvotes: 5

Related Questions