Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

ruby on rails - check if string is base64

i may recieve these two strings:

    base = Base64.encode64(File.open("/home/usr/Desktop/test", "rb").read)
    => "YQo=
"

    string = File.open("/home/usr/Desktop/test", "rb").read
    => "a
"

what i have tried so far is to check string with regular expression i-e. /([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==$)/ but this would be very heavy if the file is big.

I also have tried base.encoding.name and string.encoding.name but both returns the same.

I have also seen this post and got regular expression solution but any other solution ?

Any idea ? I just want to get is the string is actually text or base64 encoded text....

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use something like this, not very performant but you are guaranteed not to get false positives:

require 'base64'

def base64?(value)
  value.is_a?(String) && Base64.strict_encode64(Base64.decode64(value)) == value
end

The use of strict_encode64 versus encode64 prevents Ruby from inadvertently inserting newlines if you have a long string. See this post for details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...