如何使用 SecureRandom.urlsafe_base64?

How to use SecureRandom.urlsafe_base64?

我对此很陌生,需要创建一个 2 到 20 个字符的 url 安全令牌,并且只允许使用字母数字字符(字母和数字)。我使用此令牌由支付提供商进行处理。

我有下面的方法,但我收到令牌无效的错误。我如何重写该方法,使其仍然 url 安全但不超过 20 个字符并且仅使用字母数字字符?

token = SecureRandom.urlsafe_base64

As per documentation SecureRandom.urlsafe_base64 将 return “-” 和 “_” 是您说过不想要的字符。

您可以使用 SecureRandom.hex(n) 获取包含 a-z 和 0-9 的 2*n 个字符。它仍然 URL 安全。您的最终代码将是:

token = SecureRandom.hex # without `n` token will be 16 characters long.