changeset 719:bcdf320dabf4 default tip

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 1f8218896f2a
children
files bin/ed2k bin/ed2k.py
diffstat 2 files changed, 25 insertions(+), 43 deletions(-) [+]
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;
+}
--- a/bin/ed2k.py	Mon Dec 19 05:46:25 2022 +0900
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,19 +0,0 @@
-#!/usr/bin/env python
-
-import os, sys
-from Crypto.Hash import MD4
-
-def ed2k(filename):
-  block = 9500*1024
-  hash = ""
-  file = open(filename, "rb")
-  fileblock = file.read(block)
-  while fileblock:
-    hash += MD4.new(fileblock).digest()
-    fileblock = file.read(block)
-  file.close()
-  return MD4.new(hash).hexdigest()
-
-if __name__ == "__main__":
-  for file in sys.argv[1:]:
-    print "%s %s" %(ed2k(file), file)