Mercurial > ec-dotfiles
diff bin/ed2k @ 719:bcdf320dabf4
Rewrite the ed2k again in php
Getting openssl to hash md4 is a pain.
author | nanaya <me@nanaya.net> |
---|---|
date | Sun, 10 Dec 2023 00:35:22 +0900 |
parents | 94ee419ad047 |
children |
line wrap: on
line diff
--- a/bin/ed2k Mon Dec 19 05:46:25 2022 +0900 +++ b/bin/ed2k Sun Dec 10 00:35:22 2023 +0900 @@ -1,26 +1,27 @@ -#!/usr/bin/env ruby -require 'openssl' +#!/usr/bin/env php +<?php + +function ed2k_hash(string $path): string +{ + // ed2k hash is an md4 hash of concatenated binary md4 hashes of 9500 KiB file chunks. + static $bs = 9500 * 1024; + $hash = ''; + $fp = fopen($path, 'rb'); -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 + while (!feof($fp)) { + $hash .= hash('md4', fread($fp, $bs), true); + } + fclose($fp); + + return hash('md4', $hash); +} -ARGV.each do |file_name| - next unless File.file?(file_name) and File.readable?(file_name) - printf("%s\n", file_ed2k(file_name,"link")) -end +for ($i = 1; $i < $argc; $i++) { + $path = $argv[$i]; + $hash = ed2k_hash($path); + $filename = basename($path); + $filesize = filesize($path); + + echo "ed2k://|file|{$filename}|{$filesize}|{$hash}|"; + echo PHP_EOL; +}