philiprehberger-base64_url

Tests Gem Version Last updated

URL-safe Base64 encoding with optional padding and JSON helpers

Requirements

  • Ruby >= 3.1

Installation

Add to your Gemfile:

gem "philiprehberger-base64_url"

Or install directly:

gem install philiprehberger-base64_url

Usage

require "philiprehberger/base64_url"

encoded = Philiprehberger::Base64Url.encode('hello world')
# => "aGVsbG8gd29ybGQ"

decoded = Philiprehberger::Base64Url.decode(encoded)
# => "hello world"

Padding Control

require "philiprehberger/base64_url"

Philiprehberger::Base64Url.encode("Hello")                  # => "SGVsbG8" (no padding)
Philiprehberger::Base64Url.encode("Hello", padding: true)    # => "SGVsbG8=" (with padding)

Validation

Philiprehberger::Base64Url.valid?("aGVsbG8")   # => true
Philiprehberger::Base64Url.valid?("!!!")        # => false

JSON Helpers

token = Philiprehberger::Base64Url.encode_json({ user_id: 42, role: 'admin' })
# => URL-safe Base64 string

payload = Philiprehberger::Base64Url.decode_json(token)
# => {"user_id"=>42, "role"=>"admin"}

Constant-Time Comparison

token_a = Philiprehberger::Base64Url.encode("secret")
token_b = params[:token]

Philiprehberger::Base64Url.secure_compare(token_a, token_b) # => true/false

Decoded Size

Philiprehberger::Base64Url.byte_length("aGVsbG8gd29ybGQ") # => 11

File Helpers

encoded = Philiprehberger::Base64Url.encode_file("image.png")
Philiprehberger::Base64Url.decode_to_file(encoded, "copy.png")

Convert between URL-safe and standard Base64

Philiprehberger::Base64Url.to_std("SGVsbG8")    # => "SGVsbG8="
Philiprehberger::Base64Url.to_std("a-b_c")       # => "a+b/c==="

Philiprehberger::Base64Url.from_std("SGVsbG8=")  # => "SGVsbG8"
Philiprehberger::Base64Url.from_std("a+b/c==")   # => "a-b_c"

API

Method Description
.encode(data, padding: false) Encode data to URL-safe Base64 (optional padding)
.decode(data) Decode a URL-safe Base64 string
.encode_json(hash) Encode a hash as JSON then URL-safe Base64
.decode_json(str) Decode a URL-safe Base64 string and parse as JSON
.valid?(data) Check if a string is valid URL-safe Base64
.secure_compare(a, b) Constant-time comparison of two strings
.byte_length(encoded) Calculate decoded byte count without decoding
.encode_file(path, padding: false) Encode a file's contents to URL-safe Base64
.decode_to_file(encoded, path) Decode and write to a file
.to_std(data) Convert URL-safe Base64 to standard Base64 (adds = padding, swaps -_ for +/)
.from_std(data) Convert standard Base64 to URL-safe Base64 (strips = padding, swaps +/ for -_)

Development

bundle install
bundle exec rspec
bundle exec rubocop

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT