check if string is base64

2020-03-20 08:53发布

i may recieve these two strings:

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

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

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....

1条回答
smile是对你的礼貌
2楼-- · 2020-03-20 09:55

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.encode64(Base64.decode64(value)) == value
end
查看更多
登录 后发表回答