Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is base 64 encoded in Ruby?

Tags:

ruby

I have to implement some code in Ruby based on Java implementation that was already done in the company. Parts of the Java code has the usage for checking if a string is base64 encoded using Base64.isArrayByteBase64(aInput) from org.apache.commons.codec.binary.Base64 library.

I did see that the Ruby's standard library includes a module Base64 to encode and decode from and to Base64. But I don't see any functionality built into Ruby that checks if a particular string is Base64 encoded or not. Is there any other library/gem out there that fulfills my requirement?

Thanks in advance.

like image 723
Dharam Gollapudi Avatar asked Aug 27 '10 17:08

Dharam Gollapudi


2 Answers

You could do a quick check with a regular expression. Something like [A-Za-z0-9+\/]+={0,3} is pretty close. Then check to see if the length is divisible by 4.

http://en.wikipedia.org/wiki/Base64

like image 69
Lou Franco Avatar answered Oct 15 '22 08:10

Lou Franco


%r{^(?:[a-zA-Z0-9+/]{4})*(?:|(?:[a-zA-Z0-9+/]{3}=)|(?:[a-zA-Z0-9+/]{2}==)|(?:[a-zA-Z0-9+/]{1}===))$}

Is the proper regexp for rfc4648.

Ref.

like image 25
noraj Avatar answered Oct 15 '22 10:10

noraj