Groovy Cookbook

How to generate a random password in Groovy?

Sometimes you need to generate a random password (or just random string of any kind.) Today I will show you how to do it with a single line of code in Groovy 3 (or newer.)

The complete code that generates a random password in Groovy looks like this:

('0'..'z').shuffled().take(10).join()

Let’s deconstruct this example and understand what each part of this code mean.

The first part of that code ('0'..'z') creates a range of characters. If we convert it to a list, we would get a list of the following characters:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, :, ;, <, =, >, ?, @, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, [, \, ], ^, _, `, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]

As you can see, the list contains:

  • lower-case letters,

  • upper-case letters,

  • digits,

  • and several special characters.

In the next part, we call shuffled() method on the generated range to convert it to a list and shuffle the order of its elements.

Keep in mind that the shuffled() method was introduced in Groovy 3.0.

Once the list of characters is shuffled, we take the first ten elements from it using the take(10) method call.

And last but not least, we call join() method to create a string from a list of characters.

The example shown in this blog post does not guarantee that the generated password contains e.g. at least one special character and/or one digit.
Groovy Shell (4.0.0, JVM: 11.0.10)
Type ':help' or ':h' for help.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
groovy:000> ('0'..'z').shuffled().take(10).join()
===> [email protected]?nIv
groovy:000> ('0'..'z').shuffled().take(10).join()
===> O]TR84[syY
groovy:000> ('0'..'z').shuffled().take(10).join()
===> vx^[rM4g<d
groovy:000> ('0'..'z').shuffled().take(10).join()
===> 2Cv7AYgcSd
groovy:000> ('0'..'z').shuffled().take(10).join()
===> 7i`Zf[IRDy
groovy:000> ('0'..'z').shuffled().take(10).join()
===> ClKIjVTxcB
groovy:000> ('0'..'z').shuffled().take(10).join()
===> bU^[G5oE?T
groovy:000> ('0'..'z').shuffled().take(10).join()
===> tf\MmJ=SHp

Did you like this article?

Consider buying me a coffee

0 Comments