2016-08-31 16 views
1

我試圖解密一些數據,我從API中獲取並獲取一些奇怪的錯誤。NoMethodError嘗試使用Blowfish解密數據時

一些背景

使用河豚被加密,然後編碼爲一個base64字符串,並以JSON字符串提供我獲取數據。下面是什麼JSON字符串看起來像

{"payload":"BR0UzF38W4oVB7fjP6WgClqdaMKIYTl661mpneqoXQYIYkBQvjlMQZ+yn...."} 

在我的Ruby腳本,我做一個樣本如下:

require 'crypt/blowfish' 
require 'base64' 

# get json data 
response = Net::HTTP.get(URI('http://www.url-to-json.com')) 
results = JSON.parse(response) 

# decode the base64 results 
decoded = Base64.decode64(results['payload']) 

# setup blowfish object with key 
blowfish = Crypt::Blowfish.new('my_secret_key') 

# decrypt the data 
puts blowfish.decrypt_string(decoded) 

這是返回的錯誤:

/Users/Ken/.rvm/gems/[email protected]/gems/crypt-2.2.1/lib/crypt/stringxor.rb:4:in `^': undefined method `b' for "java.uti":String (NoMethodError) 
    from /Users/Ken/.rvm/gems/[email protected]/gems/crypt-2.2.1/lib/crypt/cbc.rb:62:in `decrypt_stream' 
    from /Users/Ken/.rvm/gems/[email protected]/gems/crypt-2.2.1/lib/crypt/cbc.rb:115:in `decrypt_string' 
    from /Users/Ken/Code/vs/scripts/test.rb:55:in `run' 
    from init.rb:43:in `<main>' 

你對導致這種錯誤的原因有任何瞭解嗎?我一直在調試它幾個小時,似乎無法取得任何進展。我最好的猜測是這是一個編碼問題,但是當我使用force_encoding()強制編碼時,我得到相同的錯誤。

如果你想知道我被鎖定到這個應用程序的Ruby版本1.9.3-p327。

在此先感謝您的幫助!

+0

看起來像crypt gem中的一個bug,但無法確認。當您提供手工製作的數據時,它會起作用嗎? – Felix

回答

3

罪魁禍首是這個b方法。它被引入Ruby 2.0。正如你在文檔中看到的那樣,它正在用ASCII-8BIT編碼返回一個字符串的副本。您可以更新ruby版本或monkey-patch字符串類來添加此方法。它通常用C實現,但我認爲這個Ruby實現也可以工作:

class String 
    def b 
    self.dup.force_encoding("ASCII-8BIT") 
    end 
end 
+0

工作正常!謝謝! – Ken