A Simple Token Generator

A Simple Token Generator
Photo by Edge2Edge Media / Unsplash

My friend's given me a perfect tip: "Whenever I need a random sequence of characters,  I use OpenSSL rand functions."  And to be a bit fancy, I pick the value that is easy to remember.  

So, when I need a token for QA tests, I generate a line that starts with "Qa" or "qa." Naturally, you need a lot of runs to hit the mark. So, I ended up with a one-line bash script that produced a random sequence of my choice.

rc=1; while [[ $rc -ne 0 ]]; do openssl rand -base64 32 |grep -ie '^Qa';rc=$?; done
Random sequence example

Let's go through the parts of it.

  1. rc=1 - Initialize flag variable to run OpenSSL at least once.
  2. while [[ $rc -ne 0]]; do - Enter into the while loop until rc does not equal 0.
  3. openssl rand -base64 27 - Generate a random 27-byte sequence and print it in base64 format. The length 27 has two reasons - it's odd, and you have no alignment "==" characters at the end. For different conditions, you may want to play a bit with the lengths and look of the result.
  4. grep -e '^Qa' - Filters out results from ##3 by regexp mask. You can use different conditions to get a sequence that fits your purpose. This particular one says: "String starts with Qa, exactly." If you don't mind a case, you can use grep -ie '^Qa', it will find any combinations of Qq and Aa at the beginning of the line.
  5. rc=$? - Assign the last execution result to the flag variable. The last executed command is grep, so rc would be set to 0 only if a string matches the pattern, otherwise, the execution code would be different.

I hope this little script will save you a few minutes of your life.