Ruby 中 base64 编码字符串中的奇怪 [英] Strange in base64 encoded string in Ruby

查看:37
本文介绍了Ruby 中 base64 编码字符串中的奇怪 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 中内置的 Base64 库正在添加一些 ".我无法找出原因.对于这个特殊的例子:

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

irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'base64'
=> true
irb(main):003:0> str =  "1110--ad6ca0b06e1fbeb7e6518a0418a73a6e04a67054"
=> "1110--ad6ca0b06e1fbeb7e6518a0418a73a6e04a67054"
irb(main):004:0> Base64.encode64(str)
=> "MTExMC0tYWQ2Y2EwYjA2ZTFmYmViN2U2NTE4YTA0MThhNzNhNmUwNGE2NzA1
NA==
"

位于末尾的最后一个和第 6 个位置.解码器 (Base64.decode64) 完美地返回旧字符串.奇怪的是,这些 不会向编码字符串添加任何值.当我从输出字符串中删除换行符时,解码器再次完美解码.

The 's are at the last and 6th position from end. The decoder (Base64.decode64) returns back the old string perfectly. Strange thing is, these 's don't add any value to the encoded string. When I remove the newlines from the output string, the decoder decodes it again perfectly.

irb(main):005:0> Base64.decode64(Base64.encode64(str).gsub("
", '')) == str
=> true

更多的是,我使用了另一个 JS 库来生成相同输入字符串的 base64 编码输出,输出没有 .

More of this, I used an another JS library to produce the base64 encoded output of the same input string, the output comes without the 's.

这是一个错误还是其他什么?以前有人遇到过这个问题吗?

Is this a bug or anything else? Has anybody faced this issue before?

仅供参考,

$ ruby -v
ruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux]

推荐答案

因为我写了这个答案 Base64.strict_encode64(),不添加换行符.

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

文档有些令人困惑,b64encode 方法应该是每 60 个字符添加一个换行符,而 encode64 方法的例子实际上是使用 b64encode 方法.

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.

encode64 使用的 Array 类的 pack("m") 方法似乎也添加了换行符.我认为这是一个设计错误,这不是可选的.

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.

您可以自己删除换行符,或者如果您使用的是 Rails,则有 ActiveSupport::CoreExtensions::Base64::Encodingencode64s 方法.

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

这篇关于Ruby 中 base64 编码字符串中的奇怪 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆