rubyのbase 64コードの非難

3301 ワード

str_raw = "To be prepared is half the victory."
str_encoded = [str_raw].pack('m')

または
["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"].pack("m")
=> "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJT
VFVWV1hZWg==
"

 
上の2つのコードはrubyが提供するbase 64符号化関数で、便利です.
 
しかし、いくつかの特殊な需要のある人にとって、この関数は欠陥があるようです.
 
最初のクラス-コードしたい列だけを改行する必要はありません:
使用してください
               # File base64.rb, line 64
def strict_encode64(bin)
  [bin].pack("m0")
end

公式の説明:
Returns the Base64-encoded version of  bin . This method complies with RFC 4648. No line feeds are added.
 
2番目のタイプ-コードと改行は次のとおりです.
使用してください
               # File base64.rb, line 37
def encode64(bin)
  [bin].pack("m")
end

公式の説明:
Returns the Base64-encoded version of  bin . This method complies with RFC 2045. Line feeds are added to every 60 encoded characters.
 
はい、仕事が終わって、みんなhappy~早く家に帰ってご飯を食べましょう~
 
ちょっと待って、少侠は足を止めてください.実はそうではありません.
改行の形式があり、公式サイトでは「This method complies with RFC 2045」となっています.そうですか.
 
https://tools.ietf.org/html/rfc2045#section-6.8書き
Freed & Borenstein Standards Track [Page 25]
RFC 2045 Internet Message Bodies November 1996
such assurance is possible, however, when the number of octets
transmitted was a multiple of three and no "="characters are
present.
Any characters outside of the base64 alphabet are to be ignored in
base64-encoded data.
Care must be taken to use the proper octets for line breaks if base64
encoding is applied directly to text material that has not been
converted to canonical form. In particular, text line breaks must be
converted into CRLF sequences prior to base64 encoding. The
important thing to note is that this may be done directly by the
encoder rather than in a prior canonicalization step in some
implementations.
NOTE: There is no need to worry about quoting potential boundary
delimiters within base64-encoded bodies within multipart entities
because no hyphen characters are used in the base64 encoding.
 
確かに、RFC 2045では、MIMEのbase 64符号化は60文字1ラインフィードである.しかしline feedはではなくである.WikiでもPEM,RFC 2045,RFC 4880などのbase 64符号化のline feedはいずれもであることがわかるのでruby公式の説明は完全に正確ではない.
 
正しい方法は次のとおりです.
def encode64(bin)
  [bin].pack("m").gsub(/
/,"\r
") end

 
もちろんコードは検証されていません.私はあなたをからかっていません.久しぶりにrubyを使わないで、pythonは比較的に手に合います.
忘れられない第3類の人-urlのbase 64コードを要します:
               # File base64.rb, line 80
def urlsafe_encode64(bin)
  strict_encode64(bin).tr("+/", "-_")
end
            

公式の説明:
Returns the Base64-encoded version of  bin . This method complies with “Base 64 Encoding with URL and Filename Safe Alphabet” in RFC 4648. The alphabet uses ‘-’ instead of ‘+’ and ‘_’ instead of ‘/’.