Ruby blowfish difference in the last digits

a 夏天 提交于 2019-12-25 02:23:04

问题


I have some testdata key/text/encrypted from an API provider and am now trying to yield the same encrypted result with the function below, but my result diverts from the provided one in the last 16 of 241 digits. Do you have an idea, what the reason may be? I ensured, that 'bf-ecb' is the right mode, and experimented with url-encoding, but so far without success.

require 'openssl'

def encrypt(key, data)
    cipher = OpenSSL::Cipher::Cipher.new('bf-ecb').send(:encrypt)
    cipher.key = key
    result = cipher.update(data) << cipher.final

    hexed = ''
    result.each_byte { |c| hexed << '%02x' % c }
    hexed.upcase
end

UPDATE

Also trying to decrypt the example result results in an OpenSSL::Cipher::CipherError "bad decrypt"


回答1:


If your last 16 digits (=128 bits) are incorrect then it is likely there is a problem with the last block. Probably this is a problem with padding, your encryption is using one form of padding while your decryption is expecting a different padding. I suggest that you explicitly specify the padding at both sides. PKCS5 or PKCS7 are the usual choice. Faulty padding will also explain the "bad decrypt" error message.




回答2:


It was indeed a problem with the padding. I worked around it with deactivating it and implementing it by myself. So far it works.

This is how it looks like:

require 'openssl'

def encrypt(key,data)
  cipher = OpenSSL::Cipher::Cipher.new "bf-ecb"
  cipher.padding = 0
  cipher.key = key
  cipher.encrypt
  enhex(cipher.update padd data)
end
def decrypt(key,data,len)
  cipher = OpenSSL::Cipher::Cipher.new "bf-ecb"
  cipher.padding = 0
  cipher.key = key
  cipher.decrypt
  (cipher.update dehex(data)).slice(0,len)
end
def enhex(data)
  hexed = ''
  data.each_byte { |c| hexed << '%02x' % c }
  hexed.upcase
end
def dehex(data)
  data.scan(/../).map{ |b| b.to_i(16) }.pack('C*')
end 
def padd(data)
  data + " "*(8 - (data.length % 8))
end



回答3:


You can simply do the blowfish encryption with ecb cipher mode just like this:

def blowfish_encrypt(key,data)
  cipher = OpenSSL::Cipher::Cipher.new("bf-ecb").send :encrypt
  cipher.key = key
  cipher.update(data) << cipher.final
end

And you don't need to care about padding in this case.



来源:https://stackoverflow.com/questions/7189406/ruby-blowfish-difference-in-the-last-digits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!