Strange \n in base64 encoded string in Ruby

后端 未结 6 907
野趣味
野趣味 2020-11-29 00:05

The inbuilt Base64 library in Ruby is adding some \'\\n\'s. I\'m unable to find out the reason. For this special example:

irb(main):001:0> require \'rubyg         


        
相关标签:
6条回答
  • 2020-11-29 00:25

    Edit: Since i wrote this answer Base64.strict_encode64() was added, which does not add newlines.


    The docs are somewhat confusing, the b64encode method is supposed to add a newline for every 60th character, and the example for the encode64 method is actually using the b64encode method.

    It seems the pack("m") method for the Array class used by encode64 also adds the newlines. I would consider it a design bug that this is not optional.

    You could either remove the newlines yourself, or if you're using rails, there's ActiveSupport::CoreExtensions::Base64::Encoding with the encode64s method.

    0 讨论(0)
  • 2020-11-29 00:33

    Use strict_encode64 method. encode64 adds \n every 60 symbols

    0 讨论(0)
  • 2020-11-29 00:34

    In ruby-1.9.2 you have Base64.strict_encode64 which doesn't add that \n (newline) at the end.

    0 讨论(0)
  • 2020-11-29 00:35

    Seems they've got to be stripped/ignored, like:

    Base64.encode64(str).gsub(/\n/, '')
    
    0 讨论(0)
  • 2020-11-29 00:38

    Yeah, this is quite normal. The doc gives an example demonstrating the line-splitting. base64 does the same thing in other languages too (eg. Python).

    The reason content-free newlines are added at the encode stage is because base64 was originally devised as an encoding mechanism for sending binary content in e-mail, where the line length is limited. Feel free to replace them away if you don't need them.

    0 讨论(0)
  • 2020-11-29 00:42

    The \n added when using Base64#encode64 is correct, check this post out: https://glaucocustodio.github.io/2014/09/27/a-reminder-about-base64encode64-in-ruby/

    0 讨论(0)
提交回复
热议问题