I'm building an iPhone app with a simple signup and login.
When a user signs up/logs in, I want the Ruby (Sinatra) server to generate/fetch and return an access token for that user that the iPhone client can then send with every subsequent request using Basic Authentication over HTTPS.
I'm not yet implementing OAuth 2.0 so that third party apps can access the server. Right now, I'm just building a simple, internal API (for my own, first-party, iPhone app).
Basically, I want to generate a secret API key like Stripe's: https://manage.stripe.com/account/apikeys
For example: sk_test_NMss5Xyp42TnLD9tW9vANWMr
What's the best way to do that, say in Ruby?
How does the API key work? The API is available for developers that have a free Google Maps API key. Usage of the API is not strictly free, but they do offer $200 of free monthly usage for most users. The pricing scales to fit your particular needs and you are only charged for your API usage.
So instead of storing the key in plain text (bad) or encrypting it, we should store it as a hashed value within our database. A hashed value means that even if someone gains unauthorised access to our database, no API keys are leaked and it's all safe.
If we're talking about an API key, then the issue isn't collision and there's no relationship with hashing or uuids except the recommended final length. A key should be a random 128-bit string (or 192, or 256 if you need additional security).
The Ruby stdlib provides an entire class of secure random data generators called SecureRandom
. Whatever you want, you can probably find it there.
Stripe's keys are essentially URL-safe Base64. You can get something very similar like so:
require 'securerandom'
p "sk_test_" + SecureRandom.urlsafe_base64
(Stripe does strip out non-alphanumeric characters, but that's trivial to do with gsub if you don't want hyphens in your keys.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With