Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SecureRandom.urlsafe_base64?

I'm really new to this and need to create an url-safe token of between 2 and 20 characters and only alphanumeric chars (letters and numbers) are allowed. I use this token for processing by a payment provider.

I have the method below, but I got an error that the token was invalid. How can I rewrite the method so that it's still url-safe but does not exceed 20 characters and only uses alphanumeric chars?

token = SecureRandom.urlsafe_base64
like image 914
Marty Avatar asked Feb 03 '26 18:02

Marty


1 Answers

As per documentation SecureRandom.urlsafe_base64 will return “-” and “_” which are characters you've said you don't want.

You can use SecureRandom.hex(n) to get 2*n chars containing a-z and 0-9. It's still URL safe. Your final code will be:

token = SecureRandom.hex # without `n` token will be 16 characters long.
like image 196
Cristiano Mendonça Avatar answered Feb 06 '26 12:02

Cristiano Mendonça