MD4

From Rosetta Code
Task
MD4
You are encouraged to solve this task according to the task description, using any language you may know.

Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language.

MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.

RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.

AutoHotkey

<lang AutoHotkey>rosetta := "Rosetta Code"

MsgBox % "String:`t" rosetta "`nMD4:`t" MD4(rosetta)


MD4 ===============================================================================

MD4(string, encoding = "utf-8") {

   return CalcStringHash(string, 0x8002, encoding)

}

CalcAddrHash ======================================================================

CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) {

   static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"]
   static b := h.minIndex()
   o := ""
   if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "Uint", 24, "Uint", 0xF0000000))
   {
       if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "Uint", algid, "Uint", 0, "Uint", 0, "Ptr*", hHash))
       {
           if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "Uint", length, "Uint", 0))
           {
               if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "Uint", 2, "Ptr", 0, "Uint*", hashlength, "uint", 0))
               {
                   VarSetCapacity(hash, hashlength, 0)
                   if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "Uint", 2, "Ptr", &hash, "Uint*", hashlength, "Uint", 0))
                   {
                       Loop, % hashlength
                       {
                           v := NumGet(hash, A_Index - 1, "uchar")
                           o .= h[(v >> 4) + b] h[(v & 0xf) + b]
                       }
                   }
               }
           }
           DllCall("advapi32\CryptDestroyHash", "Ptr", hHash)
       }
       DllCall("advapi32\CryptReleaseContext", "Ptr", hProv, "Uint", 0)
   }
   return o

}

CalcStringHash ====================================================================

CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) {

   chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1
   length := (StrPut(string, encoding) - 1) * chrlength
   VarSetCapacity(data, length, 0)
   StrPut(string, &data, floor(length / chrlength), encoding)
   return CalcAddrHash(&data, length, algid, hash, hashlength)

}</lang>

Output:
String:    Rosetta Code
MD4:       A52BCFC6A0D0D300CDC5DDBFBEFE478B

Emacs Lisp

md4.el by Taro Kawagishi, originally from FLIM and included in recent Emacs, is an Elisp implementation of the MD4 algorithm. Its md4 function returns the checksum as 16 binary bytes. encode-hex-string from hex-util.el can convert that to a hex string if desired.

<lang Lisp>(require 'md4) (let* ((s "Rosetta Code")

      (m  (md4 s (length s)))) ;; m = 16 binary bytes
 (require 'hex-util)
 (encode-hex-string m))

=> "a52bcfc6a0d0d300cdc5ddbfbefe478b"</lang>

Erlang

<lang erlang> -module(md4). -export([md4/0]).

md4() ->

   <<MD4:128>> = crypto:md4("Rosetta Code"),
   io:fwrite("Rosetta Code => ~.16B~n",[MD4]).

</lang>

Rosetta Code => A52BCFC6A0D0D300CDC5DDBFBEFE478B

Go

Works with: Go 1

<lang go>package main

import (

   "code.google.com/p/go.crypto/md4"
   "fmt"

)

func main() {

   h := md4.New()
   h.Write([]byte("Rosetta Code"))
   fmt.Printf("%x\n", h.Sum(nil))

}</lang>

Output:
a52bcfc6a0d0d300cdc5ddbfbefe478b

Java

Library: BouncyCastle

<lang java>import org.bouncycastle.crypto.digests.MD4Digest; import org.bouncycastle.util.encoders.Hex;

public class RosettaMD4 {

   public static void main (String[] argv) throws Exception
   {
       byte[] r = "Rosetta Code".getBytes("US-ASCII");
       MD4Digest d = new MD4Digest();
       d.update (r, 0, r.length);
       byte[] o = new byte[d.getDigestSize()];
       d.doFinal (o, 0);
       Hex.encode (o, System.out);
       System.out.println();
   }

}</lang>

Output:
a52bcfc6a0d0d300cdc5ddbfbefe478b


Lasso

<lang Lasso>cipher_digest('Rosetta Code', -digest='MD4')->encodeHex->asString</lang>

Output:
 A52BCFC6A0D0D300CDC5DDBFBEFE478B 

Perl

<lang Perl>#!/usr/bin/perl use strict ; use warnings ; use Digest::MD4 qw( md4_hex ) ;

print "Rosetta Code => " , md4_hex( "Rosetta Code" ) , "\n" ;</lang>

Output:
Rosetta Code => a52bcfc6a0d0d300cdc5ddbfbefe478b

Perl 6

<lang perl6>sub md4($str) {

   my @buf = $str.ords;
   my $buflen = @buf.elems;
   my \mask = (1 +< 32) - 1;
   my &f = -> $x, $y, $z { ($x +& $y) +| ($x +^ mask) +& $z }
   my &g = -> $x, $y, $z { ($x +& $y) +| ($x +& $z) +| ($y +& $z) }
   my &h = -> $x, $y, $z { $x +^ $y +^ $z }
   my &r = -> $v, $s { (($v +< $s) +& mask) +| (($v +& mask) +> (32 - $s)) }
   sub pack-le (@a) {
       gather for @a -> $a,$b,$c,$d { take $d +< 24 + $c +< 16 + $b +< 8 + $a }
   }

   my ($a, $b, $c, $d) = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476;

   my $term = False;
   my $last = False;
   my $off = 0;
   repeat until $last {
       my @block = @buf[$off..$off+63]:v; $off += 64;

       my @x;
       given +@block {

when 64 { @x = pack-le @block; } when 56..63 { $term = True; @block.push(0x80); @block.push(0 xx 63 - $_); @x = pack-le @block; } when 0..55 { @block.push($term ?? 0 !! 0x80); @block.push(0 xx 55 - $_); @x = pack-le @block;

my $bit_len = $buflen +< 3; @x.push: $bit_len +& mask, $bit_len +> 32; $last = True; } default { die "oops"; } }

my ($aa, $bb, $cc, $dd) = $a, $b, $c, $d; for 0, 4, 8, 12 -> \i { $a = r($a + f($b, $c, $d) + @x[ i+0 ], 3); $d = r($d + f($a, $b, $c) + @x[ i+1 ], 7); $c = r($c + f($d, $a, $b) + @x[ i+2 ], 11); $b = r($b + f($c, $d, $a) + @x[ i+3 ], 19); } for 0, 1, 2, 3 -> \i { $a = r($a + g($b, $c, $d) + @x[ i+0 ] + 0x5a827999, 3); $d = r($d + g($a, $b, $c) + @x[ i+4 ] + 0x5a827999, 5); $c = r($c + g($d, $a, $b) + @x[ i+8 ] + 0x5a827999, 9); $b = r($b + g($c, $d, $a) + @x[ i+12] + 0x5a827999, 13); } for 0, 2, 1, 3 -> \i { $a = r($a + h($b, $c, $d) + @x[ i+0 ] + 0x6ed9eba1, 3); $d = r($d + h($a, $b, $c) + @x[ i+8 ] + 0x6ed9eba1, 9); $c = r($c + h($d, $a, $b) + @x[ i+4 ] + 0x6ed9eba1, 11); $b = r($b + h($c, $d, $a) + @x[ i+12] + 0x6ed9eba1, 15); } $a = ($a + $aa) +& mask; $b = ($b + $bb) +& mask; $c = ($c + $cc) +& mask; $d = ($d + $dd) +& mask;

   }

   sub b2l($n is copy) {

my $x = 0; for ^4 { $x +<= 8; $x += $n +& 0xff; $n +>= 8; } $x;

   }
   b2l($a) +< 96 +
   b2l($b) +< 64 +
   b2l($c) +< 32 +
   b2l($d);

}

sub MAIN {

   my $str = 'Rosetta Code';
   say md4($str).base(16).lc;

}</lang>

Output:
a52bcfc6a0d0d300cdc5ddbfbefe478b

PHP

<lang php> echo hash('md4', "Rosetta Code"), "\n"; </lang>

Output:
a52bcfc6a0d0d300cdc5ddbfbefe478b


Python

Use 'hashlib' from python's standard library.

Library: hashlib

<lang python>import hashlib print hashlib.new("md4",raw_input().encode('utf-16le')).hexdigest().upper()</lang>

Racket

<lang racket>

  1. lang racket

(require (planet soegaard/digest:1:2/digest)) (md4 #"Rosetta Code") </lang> Output: <lang racket> "a52bcfc6a0d0d300cdc5ddbfbefe478b" </lang>

Ruby

Use 'openssl' from Ruby's standard library.

Library: OpenSSL

<lang ruby>require 'openssl' puts OpenSSL::Digest::MD4.hexdigest('Rosetta Code')</lang>

Implement MD4 in Ruby.

<lang ruby>require 'stringio'

  1. Calculates MD4 message digest of _string_. Returns binary digest.
  2. For hexadecimal digest, use +*md4(str).unpack('H*')+.

def md4(string)

 # functions
 mask = (1 << 32) - 1
 f = proc {|x, y, z| x & y | x.^(mask) & z}
 g = proc {|x, y, z| x & y | x & z | y & z}
 h = proc {|x, y, z| x ^ y ^ z}
 r = proc {|v, s| (v << s).&(mask) | (v.&(mask) >> (32 - s))}
 # initial hash
 a, b, c, d = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476
 io = StringIO.new(string)
 block = ""
 term = false  # appended "\x80" in second-last block?
 last = false  # last block?
 until last
   # Read next block of 16 words (64 bytes, 512 bits).
   io.read(64, block) or (
     # Work around a bug in Rubinius 1.2.4. At eof,
     # MRI and JRuby already replace block with "".
     block.replace("")
   )
   # Unpack block into 32-bit words "V".
   case len = block.length
   when 64
     # Unpack 16 words.
     x = block.unpack("V16")
   when 56..63
     # Second-last block: append padding, unpack 16 words.
     block.concat("\x80"); term = true
     block.concat("\0" * (63 - len))
     x = block.unpack("V16")
   when 0..55
     # Last block: append padding, unpack 14 words.
     block.concat(term ? "\0" : "\x80")
     block.concat("\0" * (55 - len))
     x = block.unpack("V14")
     # Append bit length, 2 words.
     bit_len = string.length << 3
     x.push(bit_len & mask, bit_len >> 32)
     last = true
   else
     fail "impossible"
   end
   # Process this block.
   aa, bb, cc, dd = a, b, c, d
   [0, 4, 8, 12].each {|i|
     a = r[a + f[b, c, d] + x[i],  3]; i += 1
     d = r[d + f[a, b, c] + x[i],  7]; i += 1
     c = r[c + f[d, a, b] + x[i], 11]; i += 1
     b = r[b + f[c, d, a] + x[i], 19]
   }
   [0, 1, 2, 3].each {|i|
     a = r[a + g[b, c, d] + x[i] + 0x5a827999,  3]; i += 4
     d = r[d + g[a, b, c] + x[i] + 0x5a827999,  5]; i += 4
     c = r[c + g[d, a, b] + x[i] + 0x5a827999,  9]; i += 4
     b = r[b + g[c, d, a] + x[i] + 0x5a827999, 13]
   }
   [0, 2, 1, 3].each {|i|
     a = r[a + h[b, c, d] + x[i] + 0x6ed9eba1,  3]; i += 8
     d = r[d + h[a, b, c] + x[i] + 0x6ed9eba1,  9]; i -= 4
     c = r[c + h[d, a, b] + x[i] + 0x6ed9eba1, 11]; i += 8
     b = r[b + h[c, d, a] + x[i] + 0x6ed9eba1, 15]
   }
   a = (a + aa) & mask
   b = (b + bb) & mask
   c = (c + cc) & mask
   d = (d + dd) & mask
 end
 [a, b, c, d].pack("V4")

end

if __FILE__ == $0

 # Print an example MD4 digest.
 str = 'Rosetta Code'
 printf "%s:\n  %s\n", str, *md4(str).unpack('H*')

end</lang>

Output:
Rosetta Code:
  a52bcfc6a0d0d300cdc5ddbfbefe478b

Seed7

<lang seed7>$ include "seed7_05.s7i";

 include "msgdigest.s7i";

const proc: main is func

 begin
   writeln(hex(md4("Rosetta Code")));
 end func;</lang>
Output:
a52bcfc6a0d0d300cdc5ddbfbefe478b

Tcl

Library: Tcllib (Package: md4)

<lang tcl>package require md4

  1. Use -hex option for hexadecimal output instead of binary

puts [md4::md4 -hex "Rosetta Code"]</lang>

Output:
A52BCFC6A0D0D300CDC5DDBFBEFE478B