2013-03-08 197 views
3

任何人都可以在這裏幫我瞭解,當我們需要考慮 以下4種方法:混淆的base64類方法的用法

strict_decode64(str) 
strict_encode64(bin) 
urlsafe_encode64(bin) 
urlsafe_decode64(str) 

從DOC我也沒有得到任何的例子。因此,帶有 解釋的示例可能對我的理解有幫助。

預先感謝

+0

什麼是[該文檔]不清楚( http://ruby-doc.org/stdlib-2.0/libdoc/base64/rdoc/Base64.html)? – steenslag 2013-03-08 19:32:19

+0

文檔缺乏示例。那裏只有幾句話。因此無法理解它的用法。它實際上意味着什麼樣的嚴格性,普通的「編碼」和「解碼」不能做什麼? – 2013-03-08 19:33:54

回答

3

_encode_decode做相反的事情:第一個正常的字符串轉換成編碼的字符串,和第二個轉換的編碼的字符串轉換成正常的字符串。

str = "Hello!" 
str == decode64(encode64(str)) # This is true 

strict_urlsafe_之間的區別是,將已編碼的字符串內使用的字符。當您需要在URL中傳遞字符串時,不允許使用所有字符(例如/,因爲它在URL中有特殊含義),因此您應該使用urlsafe_版本。

2

使用的一個例子是:

require "base64" 
Base64.strict_encode64('Stuff to be encoded') 
Base64.strict_decode64("U3R1ZmYgdG8gYmUgZW5jb2RlZA==") 

嚴格裝置,其白空間/ CR/LF是在譯碼被拒絕,並在編碼不添加CR/LF。

注意,如果如下因素被接受:

Base64.decode64("U3R1ZmYgdG8gYmUgZW5jb2RlZA==\n") 

上述嚴格是不能接受的,因爲尾隨\n(換行)和下面的行會拋出ArgumentError: invalid base64異常:

Base64.strict_decode64("U3R1ZmYgdG8gYmUgZW5jb2RlZA==\n") 

所以嚴格接受/只需要在解碼時的字母數字字符,並在編碼時只返回字母數字。

請嘗試以下,看看一個編碼包裝每60個字符的線條與'\n'(換行)和嚴格沒有:

print Base64.encode64('I will not use spaces and new lines. I will not use spaces and new lines. I will not use spaces and new lines. I will not use spaces and new lines.I will not use spaces and new lines.') 


print Base64.strict_encode64('I will not use spaces and new lines. I will not use spaces and new lines. I will not use spaces and new lines. I will not use spaces and new lines.I will not use spaces and new lines.') 
+0

@iAmRubuuu增加了一個例子希望它有幫助 – 2013-03-08 19:59:49

+0

@iAmRubuuu上述兩個例子都用於* str *,* bin *表示其他二進制表示被使用,但它仍然是一個字符串ex:'Base64.strict_encode64(「\ xaa \ xab \ xac \ xad「)',''Base64.strict_decode64(」\ x553R1ZmYgdG8gYmUgZW5jb2RlZA ==「)'注意在答案的例子中'U'被替換爲'\ x55' – 2013-03-09 06:55:11