bcrypt_engine.rb 1007 B

12345678910111213141516171819202122232425262728293031323334
  1. require 'ffi'
  2. module BCrypt
  3. class Engine
  4. extend FFI::Library
  5. BCRYPT_MAXSALT = 16
  6. BCRYPT_SALT_OUTPUT_SIZE = 7 + (BCRYPT_MAXSALT * 4 + 2) / 3 + 1
  7. BCRYPT_OUTPUT_SIZE = 128
  8. ffi_lib File.expand_path("../bcrypt_ext", __FILE__)
  9. attach_function :ruby_bcrypt, [:buffer_out, :string, :string], :string
  10. attach_function :ruby_bcrypt_gensalt, [:buffer_out, :uint8, :pointer], :string
  11. def self.__bc_salt(cost, seed)
  12. buffer_out = FFI::Buffer.alloc_out(BCRYPT_SALT_OUTPUT_SIZE, 1)
  13. seed_ptr = FFI::MemoryPointer.new(:uint8, BCRYPT_MAXSALT)
  14. seed.bytes.to_a.each_with_index { |b, i| seed_ptr.int8_put(i, b) }
  15. out = ruby_bcrypt_gensalt(buffer_out, cost, seed_ptr)
  16. seed_ptr.free
  17. buffer_out.free
  18. out || ""
  19. end
  20. def self.__bc_crypt(key, salt, cost)
  21. buffer_out = FFI::Buffer.alloc_out(BCRYPT_OUTPUT_SIZE, 1)
  22. out = ruby_bcrypt(buffer_out, key || "", salt)
  23. buffer_out.free
  24. out && out.any? ? out : nil
  25. end
  26. end
  27. end