DEV Community

Cover image for Easiest way to create secure and random strings for your JWT, session and cookie secrets.
Mohammed Imran
Mohammed Imran

Posted on

Easiest way to create secure and random strings for your JWT, session and cookie secrets.

While in development or even in production, I just find it difficult to come up with secrets for my JWTs, cookies, sessions, etc...

I first came across openssl rand command in next-auth's docs.

It is as simple as

openssl rand -base64 40
Enter fullscreen mode Exit fullscreen mode

But, can we build on it to make our lives easier with xclip to copy the output directly it into the clipboard.

openssl rand -base64 40 | xclip -r -selection clipboard
Enter fullscreen mode Exit fullscreen mode

Explaining openssl

  • The openssl program is a command line tool for using the various cryptography functions of OpenSSL's crypto library from the shell.
  • rand : Generate pseudo-random bytes.
  • -base64 : Converts the bytes into base64 encoded string.
  • Length : In the example, I've used 40 which just means 40 random bytes will be generated and that will be encoded into base64.

Explaining xclip -tags

  • -r or -rmlastnl : When the last character of the selection is a newline character, remove it. Newline characters that are not the last character in the selection are not affected. If the selection does not end with a newline character, this option has no effect. This option is useful for copying one-line output of programs like pwd to the clipboard to paste it again into the command prompt without executing the line immediately due to the character pwd appends.
  • -selection : Specify which X selection to use, options are "primary" to use XA_PRIMARY (default), "secondary" for XA_SECONDARY or "clipboard" for XA_CLIPBOARD. I usually use clipboard, since I haven't found a good use case for the other options in my workflow.

Top comments (0)