Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 encode with no padding on ruby 2.2

Tags:

ruby

base64

I'm attempting to base64 encode some things in ruby 2.2 (environment limitation) without padding. I know that in ruby 2.3 the base64 library added a padding flag that can do this for me. However, when I attempt to do this myself in ruby 2.2 using

Base64.urlsafe_encode464(str).gsub('=', '')

This creates issues for me when decoding however. Is there a way to update to the latest base64 library while staying on ruby 2.2? Or is there a good way to do a urlsafe base64 encoding that will decode correctly?

like image 810
jsookiki Avatar asked Apr 25 '26 06:04

jsookiki


1 Answers

MRI Ruby versions < 2.3.x do not support decoding Base64 content without padding (where the encoded content originally had it).

The following Ruby bug report shows the history of a change to support removal of padding and decoding without it for Ruby 2.3 and beyond. However if you try to use the 'padding' arg that was added in an older version of Ruby it fails with an ArgumentError. This makes it hard to support no-padding encode/decode across older and newer Rubies.

https://bugs.ruby-lang.org/issues/10740

A nice solution I found is the 'base64url' gem which works across Ruby versions and automatically removes and re-adds padding as needed on encode/decode. Its lightweight and only has about 11 lines of code.

https://github.com/nojima/base64url

like image 98
Glenn Rempe Avatar answered Apr 27 '26 04:04

Glenn Rempe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!