如何使用rails secure_compare?

Spi*_*ion 5 security ruby-on-rails

我努力了

line:60  mv = ActiveSupport::MessageVerifier.new
         return nil unless mv.secure_compare(a, b)
Run Code Online (Sandbox Code Playgroud)

这给出了错误

ArgumentError - wrong number of arguments (0 for 1..2):
activesupport (4.0.3) lib/active_support/message_verifier.rb:29:in `initialize'
app/controllers/application_controller.rb:60:in `new'
Run Code Online (Sandbox Code Playgroud)

http://apidock.com/rails/ActiveSupport/MessageVerifier/secure_compare

编辑

主动支持方法是私有的,因此我只是将该方法直接复制到应用程序控制器中。

   def secure_compare(a, b)
    return false unless a.bytesize == b.bytesize

    l = a.unpack "C#{a.bytesize}"

    res = 0
    b.each_byte { |byte| res |= byte ^ l.shift }
    res == 0
  end
Run Code Online (Sandbox Code Playgroud)

这样做或使用此实现是否存在任何明显的安全问题?

Vol*_*ldy 8

secure_compare自 Rails 4.2.0 起,是 ActiveSupport::SecurityUtils 的公共类方法https://api.rubyonrails.org/classes/ActiveSupport/SecurityUtils.html#method-c-secure_compare

使用示例:

def authenticate_by_token
  authenticate_with_http_token do |token, options|
    user = User.find_by(id: options[:uid])
    if user && ActiveSupport::SecurityUtils.secure_compare(user.auth_token, token)
      @current_user = user
    end
  end
end
Run Code Online (Sandbox Code Playgroud)