ed2k hash using ruby

I’ve created ed2k hashing implementation using ruby. It’s not too slow and only use core library (openssl).

def file_ed2k(file_name, output_mode = "hash")
  ed2k_block = 9500*1024 #ed2k block size is 9500 KiB
  ed2k_hash = ""
  file = File.open(file_name, 'rb')
  file_size = file.stat.size #while at it, fetch the size of the file
  while (block = file.read(ed2k_block)) do
    ed2k_hash < < OpenSSL::Digest::MD4.digest(block) #hashes are concatenated md4 per block size for ed2k hash
  end
  ed2k_hash << OpenSSL::Digest::MD4.digest("") if file_size % ed2k_block == 0 #on size of modulo block size, append another md4 hash of a blank string
  file.close
  ed2k_hash = OpenSSL::Digest::MD4.hexdigest(ed2k_hash) #finally
  return case output_mode #there are 2 modes, just the has, or complete with link.
    when "hash"
      ed2k_hash
    when "link"
      "ed2k://|file|#{File.basename(file_name)}|#{file_size}|#{ed2k_hash}|"
    end
end

You can then call the file_ed2k method (or whatever you name it) to calculate a file’s ed2k hash. ed2k link generation was created to reduce amount of IO involved when reading the file(s).

Leave a Reply

Your email address will not be published. Required fields are marked *