comparison 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
comparison
equal deleted inserted replaced
718:1f8218896f2a 719:bcdf320dabf4
1 #!/usr/bin/env ruby 1 #!/usr/bin/env php
2 require 'openssl' 2 <?php
3 3
4 def file_ed2k(file_name, output_mode = "hash") 4 function ed2k_hash(string $path): string
5 ed2k_block = 9500*1024 #ed2k block size is 9500 KiB 5 {
6 ed2k_hash = "" 6 // ed2k hash is an md4 hash of concatenated binary md4 hashes of 9500 KiB file chunks.
7 file = File.open(file_name, 'rb') 7 static $bs = 9500 * 1024;
8 file_size = file.stat.size #while at it, fetch the size of the file 8 $hash = '';
9 while (block = file.read(ed2k_block)) do 9 $fp = fopen($path, 'rb');
10 ed2k_hash << OpenSSL::Digest::MD4.digest(block) #hashes are concatenated md4 per block size for ed2k hash
11 end
12 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
13 file.close
14 ed2k_hash = OpenSSL::Digest::MD4.hexdigest(ed2k_hash) #finally
15 return case output_mode #there are 2 modes, just the has, or complete with link.
16 when "hash"
17 ed2k_hash
18 when "link"
19 "ed2k://|file|#{File.basename(file_name)}|#{file_size}|#{ed2k_hash}|"
20 end
21 end
22 10
23 ARGV.each do |file_name| 11 while (!feof($fp)) {
24 next unless File.file?(file_name) and File.readable?(file_name) 12 $hash .= hash('md4', fread($fp, $bs), true);
25 printf("%s\n", file_ed2k(file_name,"link")) 13 }
26 end 14 fclose($fp);
15
16 return hash('md4', $hash);
17 }
18
19 for ($i = 1; $i < $argc; $i++) {
20 $path = $argv[$i];
21 $hash = ed2k_hash($path);
22 $filename = basename($path);
23 $filesize = filesize($path);
24
25 echo "ed2k://|file|{$filename}|{$filesize}|{$hash}|";
26 echo PHP_EOL;
27 }