Home > Back-end >  Is there a way to generate an alphanumeric string in lua?
Is there a way to generate an alphanumeric string in lua?

Time:06-09

I want to generate a random alphanumeric string with a custom length in Lua. I'm using this as a password cracker to show my friends and I know Lua is a pretty fast language. Is there a way to do this?

CodePudding user response:

Yes, of course. Single-character manipulation of strings is a little bit fiddly in Lua, so perhaps the best method is to build an array of byte values corresponding to each character, then concatenate them together with a call to string.char(). I'm using math.random() to fetch random numbers here. You will probably want to call math.randomseed(os.time()) at the top of your program unless you're not bothered about generating the same sequence of passwords every time.

The online Lua documentation is perfectly readable. You should take a look at the chapters on strings and the mathmatical library (which includes the random number functions).

--[[ function returning a random alphanumeric string of length k --]]
function random_password(k)
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    n = string.len(alphabet)
    pw = {}
    for i = 1, k
    do
        pw[i] = string.byte(alphabet, math.random(n))
    end
    return string.char(table.unpack(pw))
end
  • Related