MD5/Implementation: Difference between revisions

m
→‎{{header|Raku}}: minor simplification
(→‎{{header|Go}}: Simplified more and made it closer to Wikipedia pseudocode for easier understanding)
m (→‎{{header|Raku}}: minor simplification)
 
(102 intermediate revisions by 40 users not shown)
Line 9:
** A translation of a correct implementation from another language
** A library routine in the same language; however, the source must be included here.
 
 
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
Line 25 ⟶ 26:
The MD5 Message-Digest Algorithm was developed by [[wp:RSA_SecurityRSA|RSA Data Security, Inc.]] in 1991.
 
{{alertbox|#ffff70|'''<big>Warning</big>'''<br/>Rosetta Code is '''not''' a place you should rely on for examples of code in critical roles, including security.<br/>Also, note that MD5 has been ''broken'' and should not be used in applications requiring security. For these consider [[wp:SHA2|SHA2]] or the upcoming [[wp:SHA3|SHA3]].}}
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">-V
rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
 
constants = (0.<64).map(i -> UInt32(UInt64(abs(sin(i + 1)) * 2.0 ^ 32) [&] FFFF'FFFF))
 
init_values = (UInt32(6745'2301), UInt32(EFCD'AB89), UInt32(98BA'DCFE), UInt32(1032'5476))
 
[((UInt32, UInt32, UInt32) -> UInt32)] functions
functions [+]= (b, c, d) -> (b [&] c) [|] (~b [&] d)
functions [+]= (b, c, d) -> (d [&] b) [|] (~d [&] c)
functions [+]= (b, c, d) -> b (+) c (+) d
functions [+]= (b, c, d) -> c (+) (b [|] ~d)
 
[(Int -> Int)] index_functions
index_functions [+]= i -> i
index_functions [+]= i -> (5 * i + 1) % 16
index_functions [+]= i -> (3 * i + 5) % 16
index_functions [+]= i -> (7 * i) % 16
 
F md5(=message)
V orig_len_in_bits = UInt64(8) * message.len
message.append(8'0)
L message.len % 64 != 56
message.append(0)
message.extend(bytes_from_int(orig_len_in_bits))
 
V hash_pieces = init_values
 
L(chunk_ofst) (0 .< message.len).step(64)
V (a, b, c, d) = hash_pieces
V chunk = message[chunk_ofst .+ 64]
L(i) 64
V f = :functions[i I/ 16](b, c, d)
V g = :index_functions[i I/ 16](i)
V to_rotate = a + f + :constants[i] + UInt32(bytes' chunk[4 * g .+ 4])
V new_b = UInt32(b + rotl(to_rotate, :rotate_amounts[i]))
(a, b, c, d) = (d, new_b, b, c)
L(val) (a, b, c, d)
hash_pieces[L.index] += val
 
[Byte] r
L(x) hash_pieces
r.extend([x [&] F'F, (x >> 8) [&] F'F, (x >> 16) [&] F'F, (x >> 24) [&] F'F])
R r
 
F md5_to_hex(digest)
V s = ‘’
L(d) digest
s ‘’= hex(d).lowercase().zfill(2)
R s
 
V demo = [Bytes(‘’), Bytes(‘a’), Bytes(‘abc’), Bytes(‘message digest’), Bytes(‘abcdefghijklmnopqrstuvwxyz’),
Bytes(‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789’),
Bytes(‘12345678901234567890123456789012345678901234567890123456789012345678901234567890’)]
L(message) demo
print(md5_to_hex(md5(message))‘ <= "’message.decode(‘ascii’)‘"’)</syntaxhighlight>
 
{{out}}
<pre>
d41d8cd98f00b204e9800998ecf8427e <= ""
0cc175b9c0f1b6a831c399e269772661 <= "a"
900150983cd24fb0d6963f7d28e17f72 <= "abc"
f96b697d7cb7938d525a2f31aaf161d0 <= "message digest"
c3fcd3d76192e4007dfb496cca67e13b <= "abcdefghijklmnopqrstuvwxyz"
d174ab98d277d9f5a5611c2c9f419d9f <= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
57edf4a22be3c955ac49da2e2107b67a <= "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
</pre>
 
=={{header|Ada}}==
Line 31 ⟶ 106:
 
md5.ads:
<langsyntaxhighlight Adalang="ada">package MD5 is
 
type Int32 is mod 2 ** 32;
Line 41 ⟶ 116:
function To_String (Item : MD5_Hash) return MD5_String;
 
end MD5;</langsyntaxhighlight>
 
md5.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Unchecked_Conversion;
 
package body MD5 is
Line 265 ⟶ 340:
end To_String;
 
end MD5;</langsyntaxhighlight>
 
tester.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Strings.Unbounded;
with Ada.Text_IO;
with MD5;
Line 301 ⟶ 376:
Ada.Text_IO.Put_Line (To_String (Digests (I)) & " (correct value)");
end loop;
end Tester;</langsyntaxhighlight>
 
output:
Line 331 ⟶ 406:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> PRINT FN_MD5("")
PRINT FN_MD5("a")
PRINT FN_MD5("abc")
Line 383 ⟶ 458:
REM Break chunk into sixteen 32-bit little-endian words:
FOR i% = 0 TO 15
w%(i%) = !(!^PTR(message$) + 64*chunk% + 4*i%)
NEXT i%
Line 439 ⟶ 514:
WHILE n# > &7FFFFFFF : n# -= 2^32 : ENDWHILE
WHILE n# < &80000000 : n# += 2^32 : ENDWHILE
= n#</langsyntaxhighlight>
 
=={{header|C}}==
Line 446 ⟶ 521:
=={{header|C sharp}}==
Handwritten implementation ([http://farazmahmood.wordpress.com/projects/md5-implementation-in-c/]):
<langsyntaxhighlight lang="csharp">
/// Represent digest with ABCD
sealed public class Digest
{
public uint A;
public uint B;
public uint C;
public uint D;
 
public Digest()
{
A=(uint)MD5InitializerConstant.A;
B=(uint)MD5InitializerConstant.B;
C=(uint)MD5InitializerConstant.C;
D=(uint)MD5InitializerConstant.D;
}
 
public override string ToString()
{
string st ;
st= MD5Helper.ReverseByte(A).ToString("X8")+
MD5Helper.ReverseByte(B).ToString("X8")+
MD5Helper.ReverseByte(C).ToString("X8")+
MD5Helper.ReverseByte(D).ToString("X8");
return st;
}
}
 
public class MD5
{
Line 788 ⟶ 891:
}
 
</syntaxhighlight>
</lang>
 
Standard library-based implementation:
<langsyntaxhighlight lang="csharp">
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(password);
bs = x.ComputeHash(bs); //this function is not in the above classdefinition
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
Line 801 ⟶ 904:
}
password = s.ToString();
</syntaxhighlight>
</lang>
 
{{omit from|Clojure|Unavailable bit operations}}
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">
# Array sum helper function.
sum = (array) ->
array.reduce (x, y) -> x + y
 
md5 = do ->
# Per-round shift amounts.
s = [738695, 669989, 770404, 703814]
s = (s[i >> 4] >> i % 4 * 5 & 31 for i in [0..63])
# Constants cache generated by sine.
K = (Math.floor 2**32 * Math.abs Math.sin i for i in [1..64])
# Bitwise left rotate helper function.
lrot = (x, y) ->
x << y | x >>> 32 - y;
(input) ->
# Initialize values.
d0 = 0x10325476;
a0 = 0x67452301;
b0 = ~d0
c0 = ~a0;
# Convert the message to 32-bit words, little-endian.
M =
for i in [0...input.length] by 4
sum (input.charCodeAt(i + j) << j*8 for j in [0..3])
# Pre-processing: append a 1 bit, then message length % 2^64.
len = input.length * 8
M[len >> 5] |= 128 << len % 32
M[(len + 64 >>> 9 << 4) + 14] = len
# Process the message in chunks of 16 32-bit words.
for x in [0...M.length] by 16
[A, B, C, D] = [a0, b0, c0, d0]
# Main loop.
for i in [0..63]
if i < 16
F = B & C | ~B & D
g = i
else if i < 32
F = B & D | C & ~D
g = i * 5 + 1
else if i < 48
F = B ^ C ^ D
g = i * 3 + 5
else
F = C ^ (B | ~D)
g = i * 7
[A, B, C, D] =
[D, B + lrot(A + F + K[i] + (M[x + g % 16] ? 0), s[i]), B, C]
a0 += A
b0 += B
c0 += C
d0 += D
# Convert the four words back to a string.
return (
for x in [a0, b0, c0, d0]
(String.fromCharCode x >>> 8 * y & 255 for y in [0..3]).join ''
).join ''
</syntaxhighlight>
 
This implementation is more focused towards brevity rather than speed. Use a javascript MD5 implementation if speed is desired. Fork this code [https://gist.github.com/Higgs1/08ec61fbb250c1c92151 on github].
 
Note: this only works on byte strings. To use arbitrary Javascript strings, you must first encode as UTF-8.
 
And tests:
 
<syntaxhighlight lang="coffeescript">
str2hex = do ->
hex = ['0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
hex = (hex[x >> 4] + hex[x & 15] for x in [0..255])
(str) ->
(hex[c.charCodeAt()] for c in str).join ''
 
console.log str2hex md5 message for message in [
""
"a"
"abc"
"message digest"
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
"12345678901234567890123456789012345678901234567890123456789012345678901234567890"
]
</syntaxhighlight>
 
Output:
 
<pre>
d41d8cd98f00b204e9800998ecf8427e
0cc175b9c0f1b6a831c399e269772661
900150983cd24fb0d6963f7d28e17f72
f96b697d7cb7938d525a2f31aaf161d0
c3fcd3d76192e4007dfb496cca67e13b
d174ab98d277d9f5a5611c2c9f419d9f
57edf4a22be3c955ac49da2e2107b67a
</pre>
 
=={{header|Common Lisp}}==
This code requires the [https://github.com/cl-babel/babel BABEL] package for converting a string to an octet buffer.
 
<syntaxhighlight lang="lisp">(defpackage #:md5
(:use #:cl))
 
(in-package #:md5)
 
(require :babel)
 
(deftype word () '(unsigned-byte 32))
(deftype octet () '(unsigned-byte 8))
(deftype octets () '(vector octet))
 
(defparameter *s*
(make-array 16 :element-type 'word
:initial-contents '(7 12 17 22
5 9 14 20
4 11 16 23
6 10 15 21)))
 
(defun s (i)
(declare ((integer 0 63) i))
(aref *s* (+ (ash (ash i -4) 2)
(ldb (byte 2 0) i))))
 
(defparameter *k*
(loop with result = (make-array 64 :element-type 'word)
for i from 0 below 64
do (setf (aref result i) (floor (* (ash 1 32) (abs (sin (1+ (float i 1d0)))))))
finally (return result)))
 
(defun wrap (bits integer)
(declare (fixnum bits) (integer integer))
(ldb (byte bits 0) integer))
 
(defun integer->8octets (integer)
(declare (integer integer))
(loop for n = (wrap 64 integer) then (ash n -8)
repeat 8
collect (wrap 8 n)))
 
(defun pad-octets (octets)
(declare (octets octets))
(let* ((octets-length (length octets))
(zero-pad-length (- 64 (mod (+ octets-length 9) 64)))
(zero-pads (loop repeat zero-pad-length collect 0)))
(concatenate 'octets octets '(#x80) zero-pads (integer->8octets (* 8 octets-length)))))
 
(defun octets->words (octets)
(declare (octets octets))
(loop with result = (make-array (/ (length octets) 4) :element-type 'word)
for n from 0 below (length octets) by 4
for i from 0
do (setf (aref result i)
(dpb (aref octets (+ n 3)) (byte 8 24)
(dpb (aref octets (+ n 2)) (byte 8 16)
(dpb (aref octets (1+ n)) (byte 8 8)
(dpb (aref octets n) (byte 8 0) 0)))))
finally (return result)))
 
(defun words->octets (&rest words)
(loop for word of-type word in words
collect (ldb (byte 8 0) word)
collect (ldb (byte 8 8) word)
collect (ldb (byte 8 16) word)
collect (ldb (byte 8 24) word)))
 
(defun left-rotate (x c)
(declare (integer x) (fixnum c))
(let ((x (wrap 32 x)))
(wrap 32 (logior (ash x c)
(ash x (- c 32))))))
 
(defun md5 (string)
(declare (string string))
(loop with m = (octets->words (pad-octets (babel:string-to-octets string)))
with a0 of-type word = #x67452301
with b0 of-type word = #xefcdab89
with c0 of-type word = #x98badcfe
with d0 of-type word = #x10325476
for j from 0 below (length m) by 16
do (loop for a of-type word = a0 then d
and b of-type word = b0 then new-b
and c of-type word = c0 then b
and d of-type word = d0 then c
for i from 0 below 64
for new-b = (multiple-value-bind (f g)
(ecase (ash i -4)
(0 (values (wrap 32 (logior (logand b c)
(logand (lognot b) d)))
i))
(1 (values (wrap 32 (logior (logand d b)
(logand (lognot d) c)))
(wrap 4 (1+ (* 5 i)))))
(2 (values (wrap 32 (logxor b c d))
(wrap 4 (+ (* 3 i) 5))))
(3 (values (wrap 32 (logxor c
(logior b (lognot d))))
(wrap 4 (* 7 i)))))
(declare (word f g))
(wrap 32 (+ b (left-rotate (+ a f (aref *k* i) (aref m (+ j g)))
(s i)))))
finally (setf a0 (wrap 32 (+ a0 a))
b0 (wrap 32 (+ b0 b))
c0 (wrap 32 (+ c0 c))
d0 (wrap 32 (+ d0 d))))
finally (return (with-output-to-string (s)
(dolist (o (words->octets a0 b0 c0 d0))
(format s "~(~2,'0X~)" o))))))
 
(defun test-cases ()
(assert (string= "d41d8cd98f00b204e9800998ecf8427e"
(md5 "")))
(assert (string= "0cc175b9c0f1b6a831c399e269772661"
(md5 "a")))
(assert (string= "900150983cd24fb0d6963f7d28e17f72"
(md5 "abc")))
(assert (string= "f96b697d7cb7938d525a2f31aaf161d0"
(md5 "message digest")))
(assert (string= "c3fcd3d76192e4007dfb496cca67e13b"
(md5 "abcdefghijklmnopqrstuvwxyz")))
(assert (string= "d174ab98d277d9f5a5611c2c9f419d9f"
(md5 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")))
(assert (string= "57edf4a22be3c955ac49da2e2107b67a"
(md5 "12345678901234567890123456789012345678901234567890123456789012345678901234567890"))))</syntaxhighlight>
 
=={{header|D}}==
Line 809 ⟶ 1,145:
 
This code generates x86 assembly code by compile time functions, then mix-in the assembly code. It only works on x86 machine.
<langsyntaxhighlight lang="d">import std.bitmanip, core.stdc.string, std.conv, std.math, std.array,
std.string;
 
Line 1,055 ⟶ 1,391:
writefln("zmd5 : %8.2f M/sec ( %8.2f secs)",
megaBytes / time2, time2);
}</langsyntaxhighlight>
{{out|Output (dmd compiler)}}
<pre>md5 digest("") = D41D8CD98F00B204E9800998ECF8427E
Line 1,077 ⟶ 1,413:
 
As you see this asm is much faster than the D code compiled by dmd, but the D code compiled by ldc2 is a little faster still.
 
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Classes}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
program MD5Implementation;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.Classes;
 
type
TTestCase = record
hashCode: string;
_: string;
end;
 
var
testCases: array[0..6] of TTestCase = ((
hashCode: 'D41D8CD98F00B204E9800998ECF8427E';
_: ''
), (
hashCode: '0CC175B9C0F1B6A831C399E269772661';
_: 'a'
), (
hashCode: '900150983CD24FB0D6963F7D28E17F72';
_: 'abc'
), (
hashCode: 'F96B697D7CB7938D525A2F31AAF161D0';
_: 'message digest'
), (
hashCode: 'C3FCD3D76192E4007DFB496CCA67E13B';
_: 'abcdefghijklmnopqrstuvwxyz'
), (
hashCode: 'D174AB98D277D9F5A5611C2C9F419D9F';
_: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
), (
hashCode: '57EDF4A22BE3C955AC49DA2E2107B67A';
_: '12345678901234567890123456789' + '012345678901234567890123456789012345678901234567890'
));
shift: array of UInt32 = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
table: array[0..63] of UInt32;
 
procedure Init();
var
i: integer;
 
function fAbs(x: Extended): Extended;
begin
if x < 0 then
exit(-x);
exit(x);
end;
 
begin
for i := 0 to High(table) do
table[i] := Trunc((UInt64(1) shl 32) * fAbs(Sin(i + 1.0)));
end;
 
function Md5(s: string): TBytes;
const
BUFFER_SIZE = 16;
var
binary: TBytesStream;
buffer: Tarray<UInt32>;
messageLenBits: UInt64;
i, j, bufferIndex, count: integer;
byte_data: byte;
string_data: ansistring;
k, k1: Tarray<UInt32>;
f, rnd, sa: UInt32;
tmp: UInt64;
begin
k := [$67452301, $EFCDAB89, $98BADCFE, $10325476];
 
binary := TBytesStream.Create();
 
if not s.IsEmpty then
begin
string_data := Utf8ToAnsi(s);
binary.Write(Tbytes(string_data), length(string_data));
end;
 
byte_data := $80;
binary.Write(byte_data, 1);
 
messageLenBits := UInt64(s.Length * 8);
count := s.Length + 1;
 
while (count mod 64) <> 56 do
begin
byte_data := $00;
binary.Write(byte_data, 1);
inc(count);
end;
 
binary.Write(messageLenBits, sizeof(messageLenBits));
 
SetLength(buffer, BUFFER_SIZE);
SetLength(k1, length(k));
 
binary.Seek(0, soFromBeginning);
 
while binary.Read(buffer[0], BUFFER_SIZE * 4) > 0 do
begin
for i := 0 to 3 do
k1[i] := k[i];
 
for i := 0 to 63 do
begin
f := 0;
bufferIndex := i;
rnd := i shr 4;
case rnd of
0:
f := (k1[1] and k1[2]) or (not k1[1] and k1[3]);
1:
begin
f := (k1[1] and k1[3]) or (k1[2] and not k1[3]);
bufferIndex := (bufferIndex * 5 + 1) and $0F
end;
2:
begin
f := k1[1] xor k1[2] xor k1[3];
bufferIndex := (bufferIndex * 3 + 5) and $0F;
end;
3:
begin
f := k1[2] xor (k1[1] or not k1[3]);
bufferIndex := (bufferIndex * 7) and $0F;
end;
end;
 
sa := shift[(rnd shl 2) or (i and 3)];
 
k1[0] := k1[0] + f + buffer[bufferIndex] + table[i];
 
tmp := k1[0];
 
k1[0] := k1[3];
k1[3] := k1[2];
k1[2] := k1[1];
 
k1[1] := ((tmp shl sa) or (tmp shr (32 - sa))) + k1[1];
end;
 
for i := 0 to 3 do
k[i] := k[i] + k1[i];
end;
 
SetLength(result, BUFFER_SIZE);
 
binary.Clear;
for i := 0 to 3 do
binary.Write(k[i], 4);
 
binary.Seek(0, soBeginning);
 
binary.Read(Result, BUFFER_SIZE);
 
binary.Free;
end;
 
function BytesToString(b: TBytes): string;
var
v: byte;
begin
Result := '';
for v in b do
Result := Result + v.ToHexString(2);
end;
 
var
tc: TTestCase;
 
begin
Init;
 
for tc in testCases do
Writeln(Format('%s'#10'%s'#10, [tc.hashCode, BytesToString(md5(tc._))]));
Readln;
end.</syntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">
len md5k[] 64
proc md5init . .
for i = 1 to 64
md5k[i] = floor (0x100000000 * abs sin (i * 180 / pi))
.
.
md5init
#
proc md5 inp$ . s$ .
subr addinp
if inp4 = 1
inp[] &= 0
.
inp[len inp[]] += b * inp4
inp4 *= 0x100
if inp4 = 0x100000000
inp4 = 1
.
.
s[] = [ 7 12 17 22 7 12 17 22 7 12 17 22 7 12 17 22 5 9 14 20 5 9 14 20 5 9 14 20 5 9 14 20 4 11 16 23 4 11 16 23 4 11 16 23 4 11 16 23 6 10 15 21 6 10 15 21 6 10 15 21 6 10 15 21 ]
inp[] = [ ]
inp4 = 1
for i = 1 to len inp$
b = strcode substr inp$ i 1
addinp
.
b = 0x80
addinp
while len inp[] mod 16 <> 14 or inp4 <> 1
b = 0
addinp
.
h = len inp$ * 8
for i = 1 to 4
b = h mod 0x100
addinp
h = h div 0x100
.
inp[] &= 0
#
a0 = 0x67452301
b0 = 0xefcdab89
c0 = 0x98badcfe
d0 = 0x10325476
for chunk = 1 step 16 to len inp[] - 15
a = a0 ; b = b0 ; c = c0 ; d = d0
for i = 1 to 64
if i <= 16
h1 = bitand b c
h2 = bitand bitnot b d
f = bitor h1 h2
g = i - 1
elif i <= 32
h1 = bitand d b
h2 = bitand bitnot d c
f = bitor h1 h2
g = (5 * i - 4) mod 16
elif i <= 48
h1 = bitxor b c
f = bitxor h1 d
g = (3 * i + 2) mod 16
else
h1 = bitor b bitnot d
f = bitxor c h1
g = (7 * i - 7) mod 16
.
f = (f + a + md5k[i] + inp[chunk + g])
a = d
d = c
c = b
h1 = bitshift f s[i]
h2 = bitshift f (s[i] - 32)
b = (b + h1 + h2)
.
a0 += a ; b0 += b ; c0 += c ; d0 += d
.
s$ = ""
for a in [ a0 b0 c0 d0 ]
for i = 1 to 4
b = a mod 256
a = a div 256
for h in [ b div 16 b mod 16 ]
h += 48
if h > 57
h += 39
.
s$ &= strchar h
.
.
.
.
repeat
s$ = input
until error = 1
md5 s$ h$
print h$
.
input_data
a
abc
message digest
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
12345678901234567890123456789012345678901234567890123456789012345678901234567890
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
Pure functional implementation (slower than library function) (Link to original blog [https://zakaluka.github.io/2017/04/23/md5-in-f-functionally.html]):
<syntaxhighlight lang="f#">let fxyz x y z : uint32 = (x &&& y) ||| (~~~x &&& z)
let gxyz x y z : uint32 = (z &&& x) ||| (~~~z &&& y)
let hxyz x y z : uint32 = x ^^^ y ^^^ z
let ixyz x y z : uint32 = y ^^^ (x ||| ~~~z)
let fghi = [ fxyz; gxyz; hxyz; ixyz ] |> List.collect (List.replicate 16)
let g1Idx = id
let g2Idx i = (5 * i + 1) % 16
let g3Idx i = (3 * i + 5) % 16
let g4Idx i = (7 * i) % 16
 
let gIdxs =
[ g1Idx; g2Idx; g3Idx; g4Idx ]
|> List.collect (List.replicate 16)
|> List.map2 (fun idx func -> func idx) [ 0..63 ]
 
let s =
[ [ 7; 12; 17; 22 ]
[ 5; 9; 14; 20 ]
[ 4; 11; 16; 23 ]
[ 6; 10; 15; 21 ] ]
|> List.collect (List.replicate 4)
|> List.concat
 
let k =
[ 1...64. ] |> List.map (sin
>> abs
>> ((*) (2. ** 32.))
>> floor
>> uint32)
 
type MD5 =
{ a : uint32
b : uint32
c : uint32
d : uint32 }
 
let initialMD5 =
{ a = 0x67452301u
b = 0xefcdab89u
c = 0x98badcfeu
d = 0x10325476u }
 
let md5round (msg : uint32 []) { MD5.a = a; MD5.b = b; MD5.c = c; MD5.d = d } i =
let rotateL32 r x = (x <<< r) ||| (x >>> (32 - r))
let f = fghi.[i] b c d
let a' = b + (a + f + k.[i] + msg.[gIdxs.[i]]
|> rotateL32 s.[i])
{ a = d
b = a'
c = b
d = c }
 
let md5plus m (bs : byte []) =
let msg =
bs
|> Array.chunkBySize 4
|> Array.take 16
|> Array.map (fun elt -> System.BitConverter.ToUInt32(elt, 0))
let m' = List.fold (md5round msg) m [ 0..63 ]
{ a = m.a + m'.a
b = m.b + m'.b
c = m.c + m'.c
d = m.d + m'.d }
 
let padMessage (msg : byte []) =
let msgLen = Array.length msg
let msgLenInBits = (uint64 msgLen) * 8UL
let lastSegmentSize =
let m = msgLen % 64
if m = 0 then 64
else m
let padLen =
64 - lastSegmentSize + (if lastSegmentSize >= 56 then 64
else 0)
[| yield 128uy
for i in 2..padLen - 8 do
yield 0uy
for i in 0..7 do
yield ((msgLenInBits >>> (8 * i)) |> byte) |]
|> Array.append msg
 
let md5sum (msg : string) =
System.Text.Encoding.ASCII.GetBytes msg
|> padMessage
|> Array.chunkBySize 64
|> Array.fold md5plus initialMD5
|> (fun { MD5.a = a; MD5.b = b; MD5.c = c; MD5.d = d } ->
System.BitConverter.GetBytes a
|> (fun x -> System.BitConverter.GetBytes b |> Array.append x)
|> (fun x -> System.BitConverter.GetBytes c |> Array.append x)
|> (fun x -> System.BitConverter.GetBytes d |> Array.append x))
|> Array.map (sprintf "%02X")
|> Array.reduce (+)</syntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' version 19-10-2016
' MD5 from the Wikipedia page "MD5"
' compile with: fbc -s console
 
' macro for a rotate left
#Macro ROtate_Left (x, n) ' rotate left
(x) = (x) Shl (n) + (x) Shr (32 - (n))
#EndMacro
 
Function MD5(test_str As String) As String
 
Dim As String message = test_str ' strings are passed as ByRef's
 
Dim As UByte sx, s(0 To ...) = { 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, _
17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, _
5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, _
16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 }
 
Dim As UInteger<32> K(0 To ...) = { &Hd76aa478, &He8c7b756, &H242070db, _
&Hc1bdceee, &Hf57c0faf, &H4787c62a, &Ha8304613, &Hfd469501, &H698098d8, _
&H8b44f7af, &Hffff5bb1, &H895cd7be, &H6b901122, &Hfd987193, &Ha679438e, _
&H49b40821, &Hf61e2562, &Hc040b340, &H265e5a51, &He9b6c7aa, &Hd62f105d, _
&H02441453, &Hd8a1e681, &He7d3fbc8, &H21e1cde6, &Hc33707d6, &Hf4d50d87, _
&H455a14ed, &Ha9e3e905, &Hfcefa3f8, &H676f02d9, &H8d2a4c8a, &Hfffa3942, _
&H8771f681, &H6d9d6122, &Hfde5380c, &Ha4beea44, &H4bdecfa9, &Hf6bb4b60, _
&Hbebfbc70, &H289b7ec6, &Heaa127fa, &Hd4ef3085, &H04881d05, &Hd9d4d039, _
&He6db99e5, &H1fa27cf8, &Hc4ac5665, &Hf4292244, &H432aff97, &Hab9423a7, _
&Hfc93a039, &H655b59c3, &H8f0ccc92, &Hffeff47d, &H85845dd1, &H6fa87e4f, _
&Hfe2ce6e0, &Ha3014314, &H4e0811a1, &Hf7537e82, &Hbd3af235, &H2ad7d2bb, _
&Heb86d391 }
 
' Initialize variables
Dim As UInteger<32> A, a0 = &H67452301
Dim As UInteger<32> B, b0 = &Hefcdab89
Dim As UInteger<32> C, c0 = &H98badcfe
Dim As UInteger<32> D, d0 = &H10325476
Dim As UInteger<32> dtemp, F, g, temp
 
Dim As Long i, j
 
Dim As ULongInt l = Len(message)
' set the first bit after the message to 1
message = message + Chr(1 Shl 7)
' add one char to the length
Dim As ULong padding = 64 - ((l +1) Mod (512 \ 8)) ' 512 \ 8 = 64 char.
 
' check if we have enough room for inserting the length
If padding < 8 Then padding = padding + 64
 
message = message + String(padding, Chr(0)) ' adjust length
Dim As ULong l1 = Len(message) ' new length
 
l = l * 8 ' orignal length in bits
' create ubyte ptr to point to l ( = length in bits)
Dim As UByte Ptr ub_ptr = Cast(UByte Ptr, @l)
 
For i = 0 To 7 'copy length of message to the last 8 bytes
message[l1 -8 + i] = ub_ptr[i]
Next
 
For j = 0 To (l1 -1) \ 64 ' split into block of 64 bytes
 
A = a0 : B = b0 : C = c0 : D = d0
 
' break chunk into 16 32bit uinteger
Dim As UInteger<32> Ptr M = Cast(UInteger<32> Ptr, @message[j * 64])
 
For i = 0 To 63
Select Case As Const i
Case 0 To 15
F = (B And C) Or ((Not B) And D)
g = i
Case 16 To 31
F = (B And D) Or (C And (Not D))
g = (i * 5 +1) Mod 16
Case 32 To 47
F = (B Xor C Xor D)
g = (i * 3 +5) Mod 16
Case 48 To 63
F = C Xor (B Or (Not D))
g = (i * 7) Mod 16
End Select
dtemp = D
D = C
C = B
temp = A + F + K(i)+ M[g] : ROtate_left(temp, s(i))
B = B + temp
A = dtemp
Next
 
a0 += A : b0 += B : c0 += C : d0 += D
 
Next
 
Dim As String answer
' convert a0, b0, c0 and d0 in hex, then add, low order first
Dim As String s1 = Hex(a0, 8)
For i = 7 To 1 Step -2 : answer +=Mid(s1, i, 2) : Next
s1 = Hex(b0, 8)
For i = 7 To 1 Step -2 : answer +=Mid(s1, i, 2) : Next
s1 = Hex(c0, 8)
For i = 7 To 1 Step -2 : answer +=Mid(s1, i, 2) : Next
s1 = Hex(d0, 8)
For i = 7 To 1 Step -2 : answer +=Mid(s1, i, 2) : Next
 
Return LCase(answer)
 
End Function
 
 
' ------=< MAIN >=------
 
Dim As String test, hash, md5_hash
Dim As ULong i
 
For i = 1 To 7
Read hash, test
md5_hash = MD5(test)
 
Print
Print test
Print hash
Print md5_hash;
 
If hash = md5_hash Then
Print " PASS"
Else
Print " FAIL"
Beep
End If
 
Next
 
' testdata
Data "d41d8cd98f00b204e9800998ecf8427e", ""
Data "0cc175b9c0f1b6a831c399e269772661", "a"
Data "900150983cd24fb0d6963f7d28e17f72", "abc"
Data "f96b697d7cb7938d525a2f31aaf161d0", "message digest"
Data "c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"
Data "d174ab98d277d9f5a5611c2c9f419d9f"
Data "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Data "57edf4a22be3c955ac49da2e2107b67a"
Data "123456789012345678901234567890123456789012345678901234567890" _
+ "12345678901234567890"
 
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</syntaxhighlight>
{{out}}
<pre>
d41d8cd98f00b204e9800998ecf8427e
d41d8cd98f00b204e9800998ecf8427e PASS
 
a
0cc175b9c0f1b6a831c399e269772661
0cc175b9c0f1b6a831c399e269772661 PASS
 
abc
900150983cd24fb0d6963f7d28e17f72
900150983cd24fb0d6963f7d28e17f72 PASS
 
message digest
f96b697d7cb7938d525a2f31aaf161d0
f96b697d7cb7938d525a2f31aaf161d0 PASS
 
abcdefghijklmnopqrstuvwxyz
c3fcd3d76192e4007dfb496cca67e13b
c3fcd3d76192e4007dfb496cca67e13b PASS
 
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
d174ab98d277d9f5a5611c2c9f419d9f
d174ab98d277d9f5a5611c2c9f419d9f PASS
 
12345678901234567890123456789012345678901234567890123456789012345678901234567890
57edf4a22be3c955ac49da2e2107b67a
57edf4a22be3c955ac49da2e2107b67a PASS</pre>
 
=={{header|Go}}==
A limitation from RFC 1321 is that the function md5 takes a string, which is a number of whole bytes. Messages of arbitrary bit length are not supported.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,108 ⟶ 2,017:
func main() {
for _, tc := range testCases {
fmt.Printf("%s\n%x\n\n", tc.hashCode, md5([]byte(tc.string)))
}
}
Line 1,121 ⟶ 2,030:
}
 
func md5(s []bytestring) (r [16]byte) {
padded := bytes.NewBuffer([]byte(s))
padded.WriteByte(0x80)
for padded.Len() % 64 != 56 {
Line 1,160 ⟶ 2,069:
binary.Write(bytes.NewBuffer(r[:0]), binary.LittleEndian, []uint32{a, b, c, d})
return
}</langsyntaxhighlight>
Output:
<pre>
Line 1,184 ⟶ 2,093:
57edf4a22be3c955ac49da2e2107b67a
</pre>
 
=={{header|Groovy}}==
<syntaxhighlight lang="groovy">
class MD5 {
 
private static final int INIT_A = 0x67452301
private static final int INIT_B = (int)0xEFCDAB89L
private static final int INIT_C = (int)0x98BADCFEL
private static final int INIT_D = 0x10325476
 
private static final int[] SHIFT_AMTS = [
7, 12, 17, 22,
5, 9, 14, 20,
4, 11, 16, 23,
6, 10, 15, 21
]
 
private static final int[] TABLE_T = new int[64]
static
{
for (int i in 0..63)
TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)))
}
 
static byte[] computeMD5(byte[] message)
{
int messageLenBytes = message.length
int numBlocks = ((messageLenBytes + 8) >>> 6) + 1
int totalLen = numBlocks << 6
byte[] paddingBytes = new byte[totalLen - messageLenBytes]
paddingBytes[0] = (byte)0x80
 
long messageLenBits = (long)messageLenBytes << 3
for (int i in 0..7)
{
paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits
messageLenBits >>>= 8
}
 
int a = INIT_A
int b = INIT_B
int c = INIT_C
int d = INIT_D
int[] buffer = new int[16]
for (int i in 0..(numBlocks - 1))
{
int index = i << 6
for (int j in 0..63) {
buffer[j >>> 2] = ((int) ((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8)
index++
}
int originalA = a
int originalB = b
int originalC = c
int originalD = d
for (int j in 0..63)
{
int div16 = j >>> 4
int f = 0
int bufferIndex = j
switch (div16)
{
case 0:
f = (b & c) | (~b & d)
break
 
case 1:
f = (b & d) | (c & ~d)
bufferIndex = (bufferIndex * 5 + 1) & 0x0F
break
 
case 2:
f = b ^ c ^ d
bufferIndex = (bufferIndex * 3 + 5) & 0x0F
break
 
case 3:
f = c ^ (b | ~d)
bufferIndex = (bufferIndex * 7) & 0x0F
break
}
int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)])
a = d
d = c
c = b
b = temp
}
 
a += originalA
b += originalB
c += originalC
d += originalD
}
 
byte[] md5 = new byte[16]
int count = 0
for (int i in 0..3)
{
int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d))
for (int j in 0..3)
{
md5[count++] = (byte)n
n >>>= 8
}
}
return md5
}
 
static String toHexString(byte[] b)
{
StringBuilder sb = new StringBuilder()
for (int i in 0..(b.length - 1))
{
sb.append(String.format("%02X", b[i] & 0xFF))
}
return sb.toString()
}
 
static void main(String[] args)
{
String[] testStrings = ["", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890" ]
for (String s : testStrings)
System.out.println("0x" + toHexString(computeMD5(s.getBytes())) + " <== \"" + s + "\"")
}
 
}
 
</syntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Monad (replicateM)
 
import qualified Data.ByteString.Lazy as BL
Line 1,298 ⟶ 2,337:
w = datA ! (idxA ! i)
a' = b + (a + f b c d + w + sinA ! i) `rotateL` rotA ! i
in MD5 d a' b c</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The following program is based on part on the Wikipedia pseudo-code and in part on the reference implementation in RFC 1321. The implementation uses large integers. The solution works in both Icon and Unicon. One limitation of this implementation is that will not handle arbitrary (bit) length messages - all are byte aligned. Another small challenge was that Icon/Unicon bit manipulation functions work on signed integers (and large integers), as a result there are no native rotation and negation functions.
<langsyntaxhighlight Iconlang="icon">procedure main() # validate against the RFC test strings and more
testMD5("The quick brown fox jumps over the lazy dog", 16r9e107d9d372bb6826bd81d3542a419d6)
testMD5("The quick brown fox jumps over the lazy dog.", 16re4d909c290d0fb1ca068ffaddf22cbd0)
Line 1,403 ⟶ 2,442:
end
 
link unsigned # string to unsigned integer</langsyntaxhighlight>
 
The {{libheader|Icon Programming Library}} provides [http://www.cs.arizona.edu/icon/library/src/procs/unsigned.icn unsigned] and [http://www.cs.arizona.edu/icon/library/src/procs/hexcvt.icn hexcvt]
Line 1,422 ⟶ 2,461:
=={{header|J}}==
 
Note: the following code was originally extracted from http://www.jsoftware.com/tracwsvn/addons/browser/trunk/convert/misc/md5.ijs
 
<syntaxhighlight lang="j">NB. convert/misc/md5
<lang j>NB. RSA Data Security, Inc. MD5 Message-Digest Algorithm
NB. RSA Data Security, Inc. MD5 Message-Digest Algorithm
NB. version: 1.0.2
NB.
Line 1,432 ⟶ 2,472:
NB. 09/04/2003 Oleg Kobchenko
NB. 03/31/2007 Oleg Kobchenko j601, JAL
NB. 12/17/2015 G.Pruss 64-bit
NB. ~60+ times slower than using the jqt library
 
require 'convert'
coclass 'pcrypt'
 
NB. lt= (*. -.)~ gt= *. -. ge= +. -. xor= ~:
'`lt gt ge xor'=: (20 b.)`(18 b.)`(27 b.)`(22 b.)
'`and or rot sh'=: (17 b.)`(23 b.)`(32 b.)`(33 b.)
 
3 : 0 ''
if. IF64 do.
rot=: (16bffffffff and sh or ] sh~ 32 -~ [) NB. (y << x) | (y >>> (32 - x))
add=: ((16bffffffff&and)@+)"0
else.
rot=: (32 b.)
add=: (+&(_16&sh) (16&sh@(+ _16&sh) or and&65535@]) +&(and&65535))"0
end.
EMPTY
)
 
hexlist=: tolower@:,@:hfd@:,@:(|."1)@(256 256 256 256&#:)
 
cmn=: 4 : 0
'x s t'=. x [ 'q a b'=. y
b add s rot (a add q) add (x add t)
)
 
Line 1,453 ⟶ 2,507:
 
I=: ".;._2(0 : 0)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 6 11 0 5 10 15 4 9 14 3 8 13 2 7 12
5 8 11 14 1 4 7 10 13 0 3 6 9 12 15 2
0 7 14 5 12 3 10 1 8 15 6 13 4 11 2 9
)
S=: 4 4$7 12 17 22 5 9 14 20 4 11 16 23 6 10 15 21
 
T=: |:".;._2(0 : 0)
_680876936 _165796510 _378558 _198630844
_389564586 _1069501632 _2022574463 1126891415
606105819 643717713 1839030562 _1416354905
_1044525330 _373897302 _35309556 _57434055
_176418897 _701558691 _1530992060 1700485571
1200080426 38016083 1272893353 _1894986606
_1473231341 _660478335 _155497632 _1051523
_45705983 _405537848 _1094730640 _2054922799
1770035416 568446438 681279174 1873313359
_1958414417 _1019803690 _358537222 _30611744
_42063 _187363961 _722521979 _1560198380
_1990404162 1163531501 76029189 1309151649
1804603682 _1444681467 _640364487 _145523070
_40341101 _51403784 _421815835 _1120210379
_1502002290 1735328473 530742520 718787259
1236535329 _1926607734 _995338651 _343485551
)
 
norm=: 3 : 0
n=. 16 * 1 + _6 sh 8 + #y
b=. n#0 [ y=. a.i.y
for_i. i. #y do.
b=. ((j { b) or (8*4|i) sh i{y) (j=. _2 sh i) } b
end.
b=. ((j { b) or (8*4|i) sh 128) (j=._2 sh i=.#y) } b
_16]\ (8 * #y) (n-2) } b
)
 
Line 1,492 ⟶ 2,546:
NB. diagest=. md5 message
md5=: 3 : 0
X=. norm y
q=. r=. 1732584193 _271733879 _1732584194 271733878
for_x. X do.
for_j. i.4 do.
l=. ((j{I){x) ,. (16$j{S) ,. j{T
for_i. i.16 do.
r=. _1|.((i{l) (op@.j) r),}.r
end.
end.
q=. r=. r add q
end.
q=. r=. r add q
hexlist r
end.
)</lang>
hexlist r
)
 
md5_z_=: md5_pcrypt_</syntaxhighlight>
 
<langsyntaxhighlight lang="j"> md5''
d41d8cd98f00b204e9800998ecf8427e
md5'a'
Line 1,520 ⟶ 2,576:
md5'12345678901234567890123456789012345678901234567890123456789012345678901234567890'
57edf4a22be3c955ac49da2e2107b67a
</syntaxhighlight>
</lang>
 
 
=={{header|Java}}==
{{works with|Java|1.5+}}
Based on RFC-1321.
<syntaxhighlight lang="java">class MD5
<lang java>
class MD5
{
 
Line 1,649 ⟶ 2,703:
}
}</syntaxhighlight>
}
</lang>
 
<b>Output:</b>
Line 1,660 ⟶ 2,713:
0xD174AB98D277D9F5A5611C2C9F419D9F <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57EDF4A22BE3C955AC49DA2E2107B67A <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
</pre>
 
{{works with|Java|1.5+}}
Using <code>ByteBuffer</code>s
<syntaxhighlight lang="java">import java.nio.ByteBuffer;
import java.nio.ByteOrder;
 
class MD5
{
 
private static final int INIT_A = 0x67452301;
private static final int INIT_B = (int)0xEFCDAB89L;
private static final int INIT_C = (int)0x98BADCFEL;
private static final int INIT_D = 0x10325476;
private static final int[] SHIFT_AMTS = {
7, 12, 17, 22,
5, 9, 14, 20,
4, 11, 16, 23,
6, 10, 15, 21
};
private static final int[] TABLE_T = new int[64];
static
{
for (int i = 0; i < 64; i++)
TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)));
}
public static byte[] computeMD5(byte[] message)
{
ByteBuffer padded = ByteBuffer.allocate((((message.length + 8) / 64) + 1) * 64).order(ByteOrder.LITTLE_ENDIAN);
padded.put(message);
padded.put((byte)0x80);
long messageLenBits = (long)message.length * 8;
padded.putLong(padded.capacity() - 8, messageLenBits);
 
padded.rewind();
 
int a = INIT_A;
int b = INIT_B;
int c = INIT_C;
int d = INIT_D;
while (padded.hasRemaining()) {
// obtain a slice of the buffer from the current position,
// and view it as an array of 32-bit ints
IntBuffer chunk = padded.slice().order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
int originalA = a;
int originalB = b;
int originalC = c;
int originalD = d;
for (int j = 0; j < 64; j++)
{
int div16 = j >>> 4;
int f = 0;
int bufferIndex = j;
switch (div16)
{
case 0:
f = (b & c) | (~b & d);
break;
case 1:
f = (b & d) | (c & ~d);
bufferIndex = (bufferIndex * 5 + 1) & 0x0F;
break;
case 2:
f = b ^ c ^ d;
bufferIndex = (bufferIndex * 3 + 5) & 0x0F;
break;
case 3:
f = c ^ (b | ~d);
bufferIndex = (bufferIndex * 7) & 0x0F;
break;
}
int temp = b + Integer.rotateLeft(a + f + chunk.get(bufferIndex) + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]);
a = d;
d = c;
c = b;
b = temp;
}
a += originalA;
b += originalB;
c += originalC;
d += originalD;
padded.position(padded.position() + 64);
}
ByteBuffer md5 = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN);
for (int n : new int[]{a, b, c, d})
{
md5.putInt(n);
}
return md5.array();
}
public static String toHexString(byte[] b)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++)
{
sb.append(String.format("%02X", b[i] & 0xFF));
}
return sb.toString();
}
 
public static void main(String[] args)
{
String[] testStrings = { "", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "12345678901234567890123456789012345678901234567890123456789012345678901234567890" };
for (String s : testStrings)
System.out.println("0x" + toHexString(computeMD5(s.getBytes())) + " <== \"" + s + "\"");
return;
}
}</syntaxhighlight>
 
<b>Output:</b>
<pre>0xD41D8CD98F00B204E9800998ECF8427E <== ""
0x0CC175B9C0F1B6A831C399E269772661 <== "a"
0x900150983CD24FB0D6963F7D28E17F72 <== "abc"
0xF96B697D7CB7938D525A2F31AAF161D0 <== "message digest"
0xC3FCD3D76192E4007DFB496CCA67E13B <== "abcdefghijklmnopqrstuvwxyz"
0xD174AB98D277D9F5A5611C2C9F419D9F <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57EDF4A22BE3C955AC49DA2E2107B67A <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia"># a rather literal translation of the pseudocode at https://en.wikipedia.org/wiki/MD5
 
const s = UInt32[7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
 
const K = UInt32[0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf,
0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1,
0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562,
0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681,
0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905,
0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122,
0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6,
0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8,
0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3,
0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314,
0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391]
 
function md5(msgbytes)
a0::UInt32 = 0x67452301 # A
b0::UInt32 = 0xefcdab89 # B
c0::UInt32 = 0x98badcfe # C
d0::UInt32 = 0x10325476 # D
 
oldlen = length(msgbytes)
umsg = push!([UInt8(b) for b in msgbytes], UInt8(0x80))
while length(umsg) % 64 != 56
push!(umsg, UInt8(0))
end
append!(umsg, reinterpret(UInt8, [htol(UInt64(oldlen) * 8)]))
 
for j in 1:64:length(umsg)-1
arr = view(umsg, j:j+63)
M = [reinterpret(UInt32, arr[k:k+3])[1] for k in 1:4:62]
A = a0
B = b0
C = c0
D = d0
 
for i in 0:63
if 0 ≤ i ≤ 15
F = D ⊻ (B & (C ⊻ D))
g = i
elseif 16 ≤ i ≤ 31
F = C ⊻ (D & (B ⊻ C))
g = (5 * i + 1) % 16
elseif 32 ≤ i ≤ 47
F = B ⊻ C ⊻ D
g = (3 * i + 5) % 16
elseif 48 ≤ i ≤ 63
F = C ⊻ (B | (~D))
g = (7 * i) % 16
end
F += A + K[i+1] + M[g+1]
A = D
D = C
C = B
B += ((F) << s[i+1]) | (F >> (32 - s[i+1]))
end
 
a0 += A
b0 += B
c0 += C
d0 += D
end
digest = join(map(x -> lpad(string(x, base=16), 2, '0'), reinterpret(UInt8, [a0, b0, c0, d0])), "") # Output is in little-endian
end
 
for pair in [0xd41d8cd98f00b204e9800998ecf8427e => "", 0x0cc175b9c0f1b6a831c399e269772661 => "a",
0x900150983cd24fb0d6963f7d28e17f72 => "abc", 0xf96b697d7cb7938d525a2f31aaf161d0 => "message digest",
0xc3fcd3d76192e4007dfb496cca67e13b => "abcdefghijklmnopqrstuvwxyz",
0xd174ab98d277d9f5a5611c2c9f419d9f => "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
0x57edf4a22be3c955ac49da2e2107b67a => "12345678901234567890123456789012345678901234567890123456789012345678901234567890"]
println("MD5 of $(pair[2]) is $(md5(pair[2])), which checks with $(string(pair[1], base=16)).")
end
</syntaxhighlight>{{out}}
<pre>
MD5 of is d41d8cd98f00b204e9800998ecf8427e, which checks with d41d8cd98f00b204e9800998ecf8427e.
MD5 of a is 0cc175b9c0f1b6a831c399e269772661, which checks with cc175b9c0f1b6a831c399e269772661.
MD5 of abc is 900150983cd24fb0d6963f7d28e17f72, which checks with 900150983cd24fb0d6963f7d28e17f72.
MD5 of message digest is f96b697d7cb7938d525a2f31aaf161d0, which checks with f96b697d7cb7938d525a2f31aaf161d0.
MD5 of abcdefghijklmnopqrstuvwxyz is c3fcd3d76192e4007dfb496cca67e13b, which checks with c3fcd3d76192e4007dfb496cca67e13b.
MD5 of ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 is d174ab98d277d9f5a5611c2c9f419d9f, which checks with d174ab98d277d9f5a5611c2c9f419d9f.
MD5 of 12345678901234567890123456789012345678901234567890123456789012345678901234567890 is 57edf4a22be3c955ac49da2e2107b67a, which checks with 57edf4a22be3c955ac49da2e2107b67a.
</pre>
 
=={{header|Kotlin}}==
{{trans|Java}}
<syntaxhighlight lang="scala">// version 1.1.3
 
object MD5 {
 
private val INIT_A = 0x67452301
private val INIT_B = 0xEFCDAB89L.toInt()
private val INIT_C = 0x98BADCFEL.toInt()
private val INIT_D = 0x10325476
private val SHIFT_AMTS = intArrayOf(
7, 12, 17, 22,
5, 9, 14, 20,
4, 11, 16, 23,
6, 10, 15, 21
)
 
private val TABLE_T = IntArray(64) {
((1L shl 32) * Math.abs(Math.sin(it + 1.0))).toLong().toInt()
}
 
fun compute(message: ByteArray): ByteArray {
val messageLenBytes = message.size
val numBlocks = ((messageLenBytes + 8) ushr 6) + 1
val totalLen = numBlocks shl 6
val paddingBytes = ByteArray(totalLen - messageLenBytes)
paddingBytes[0] = 0x80.toByte()
var messageLenBits = (messageLenBytes shl 3).toLong()
 
for (i in 0..7) {
paddingBytes[paddingBytes.size - 8 + i] = messageLenBits.toByte()
messageLenBits = messageLenBits ushr 8
}
 
var a = INIT_A
var b = INIT_B
var c = INIT_C
var d = INIT_D
val buffer = IntArray(16)
 
for (i in 0 until numBlocks) {
var index = i shl 6
 
for (j in 0..63) {
val temp = if (index < messageLenBytes) message[index] else
paddingBytes[index - messageLenBytes]
buffer[j ushr 2] = (temp.toInt() shl 24) or (buffer[j ushr 2] ushr 8)
index++
}
 
val originalA = a
val originalB = b
val originalC = c
val originalD = d
 
for (j in 0..63) {
val div16 = j ushr 4
var f = 0
var bufferIndex = j
when (div16) {
0 -> {
f = (b and c) or (b.inv() and d)
}
 
1 -> {
f = (b and d) or (c and d.inv())
bufferIndex = (bufferIndex * 5 + 1) and 0x0F
}
2 -> {
f = b xor c xor d;
bufferIndex = (bufferIndex * 3 + 5) and 0x0F
}
 
3 -> {
f = c xor (b or d.inv());
bufferIndex = (bufferIndex * 7) and 0x0F
}
}
 
val temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] +
TABLE_T[j], SHIFT_AMTS[(div16 shl 2) or (j and 3)])
a = d
d = c
c = b
b = temp
}
 
a += originalA
b += originalB
c += originalC
d += originalD
}
 
val md5 = ByteArray(16)
var count = 0
 
for (i in 0..3) {
var n = if (i == 0) a else (if (i == 1) b else (if (i == 2) c else d))
 
for (j in 0..3) {
md5[count++] = n.toByte()
n = n ushr 8
}
}
return md5
}
}
 
fun ByteArray.toHexString(): String {
val sb = StringBuilder()
for (b in this) sb.append(String.format("%02x", b.toInt() and 0xFF))
return sb.toString()
}
 
fun main(args: Array<String>) {
val testStrings = arrayOf(
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890"
)
 
println("${"hash code".padStart(34)} <== string")
for (s in testStrings) {
println("0x${MD5.compute(s.toByteArray()).toHexString()} <== \"$s\"")
}
}</syntaxhighlight>
 
{{out}}
<pre>
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
</pre>
 
Line 1,665 ⟶ 3,078:
''See the implementation at [[MD5#Liberty BASIC]].''
 
=={{header|MathematicaLingo}}==
<syntaxhighlight lang="lingo">----------------------------------------
<lang Mathematica>md5[string_String] :=
-- Calculates MD5 hash of string or bytearray
-- @param {bytearray|string} input
-- @return {bytearray} (16 bytes)
----------------------------------------
on md5 (input)
if stringP(input) then input = bytearray(input)
 
-- Convert string to list of little-endian words...
t_iLen = input.length * 8
t_iCnt = (t_iLen + 64) / 512 * 16 + 16
 
-- Create list, fill with zeros...
x = []
x[t_iCnt] = 0
 
t_fArr = [1, 256, 65536, 16777216]
i = 0
j = 0
repeat while i < t_iLen
j = j + 1
t_iNext = i / 32 + 1
t_iTemp = bitAnd(input[i/8+1], 255) * t_fArr[j]
x[t_iNext] = bitOr(x[t_iNext], t_iTemp)
i = i + 8
j = j mod 4
end repeat
 
-- Append padding...
t_iNext = t_iLen / 32 + 1
x[t_iNext] = bitOr(x[t_iNext], 128 * t_fArr[j + 1])
x[(t_iLen + 64) / 512 * 16 + 15] = t_iLen
 
-- Actual algorithm starts here...
a = 1732584193
b = -271733879
c = -1732584194
d = 271733878
i = 1
t_iWrap = the maxInteger + 1
t_iCount = x.count + 1
repeat while i < t_iCount
olda = a
oldb = b
oldc = c
oldd = d
 
-- Round(1) --
n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i] - 680876936
if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b
else a = bitOr(n * 128, n / 33554432) + b
n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 1] - 389564586
if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a
else d = bitOr(n * 4096, n / 1048576) + a
n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 2] + 606105819
if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d
else c = bitOr(n * 131072, n / 32768) + d
n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 3] - 1044525330
if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c
else b = bitOr(n * 4194304, n / 1024) + c
n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i + 4] - 176418897
if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b
else a = bitOr(n * 128, n / 33554432) + b
n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 5] + 1200080426
if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a
else d = bitOr(n * 4096, n / 1048576) + a
n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 6] - 1473231341
if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d
else c = bitOr(n * 131072, n / 32768) + d
n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 7] - 45705983
if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c
else b = bitOr(n * 4194304, n / 1024) + c
n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i + 8] + 1770035416
if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b
else a = bitOr(n * 128, n / 33554432) + b
n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 9] - 1958414417
if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a
else d = bitOr(n * 4096, n / 1048576) + a
n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 10] - 42063
if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d
else c = bitOr(n * 131072, n / 32768) + d
n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 11] - 1990404162
if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c
else b = bitOr(n * 4194304, n / 1024) + c
n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i + 12] + 1804603682
if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b
else a = bitOr(n * 128, n / 33554432) + b
n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 13] - 40341101
if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a
else d = bitOr(n * 4096, n / 1048576) + a
n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 14] - 1502002290
if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d
else c = bitOr(n * 131072, n / 32768) + d
n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 15] + 1236535329
if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c
else b = bitOr(n * 4194304, n / 1024) + c
 
-- Round(2) --
n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 1] - 165796510
if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b
else a = bitOr(n * 32, n / 134217728) + b
n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 6] - 1069501632
if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a
else d = bitOr(n * 512, n / 8388608) + a
n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 11] + 643717713
if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d
else c = bitOr(n * 16384, n / 262144) + d
n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i] - 373897302
if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c
else b = bitOr(n * 1048576, n / 4096) + c
n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 5] - 701558691
if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b
else a = bitOr(n * 32, n / 134217728) + b
n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 10] + 38016083
if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a
else d = bitOr(n * 512, n / 8388608) + a
n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 15] - 660478335
if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d
else c = bitOr(n * 16384, n / 262144) + d
n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i + 4] - 405537848
if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c
else b = bitOr(n * 1048576, n / 4096) + c
n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 9] + 568446438
if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b
else a = bitOr(n * 32, n / 134217728) + b
n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 14] - 1019803690
if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a
else d = bitOr(n * 512, n / 8388608) + a
n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 3] - 187363961
if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d
else c = bitOr(n * 16384, n / 262144) + d
n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i + 8] + 1163531501
if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c
else b = bitOr(n * 1048576, n / 4096) + c
n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 13] - 1444681467
if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b
else a = bitOr(n * 32, n / 134217728) + b
n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 2] - 51403784
if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a
else d = bitOr(n * 512, n / 8388608) + a
n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 7] + 1735328473
if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d
else c = bitOr(n * 16384, n / 262144) + d
n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i + 12] - 1926607734
if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c
else b = bitOr(n * 1048576, n / 4096) + c
 
-- Round(3) --
n = bitXor(bitXor(b, c), d) + a + x[i + 5] - 378558
if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b
else a = bitOr(n * 16, n / 268435456) + b
n = bitXor(bitXor(a, b), c) + d + x[i + 8] - 2022574463
if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a
else d = bitOr(n * 2048, n / 2097152) + a
n = bitXor(bitXor(d, a), b) + c + x[i + 11] + 1839030562
if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d
else c = bitOr(n * 65536, n / 65536) + d
n = bitXor(bitXor(c, d), a) + b + x[i + 14] - 35309556
if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c
else b = bitOr(n * 8388608, n / 512) + c
n = bitXor(bitXor(b, c), d) + a + x[i + 1] - 1530992060
if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b
else a = bitOr(n * 16, n / 268435456) + b
n = bitXor(bitXor(a, b), c) + d + x[i + 4] + 1272893353
if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a
else d = bitOr(n * 2048, n / 2097152) + a
n = bitXor(bitXor(d, a), b) + c + x[i + 7] - 155497632
if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d
else c = bitOr(n * 65536, n / 65536) + d
n = bitXor(bitXor(c, d), a) + b + x[i + 10] - 1094730640
if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c
else b = bitOr(n * 8388608, n / 512) + c
n = bitXor(bitXor(b, c), d) + a + x[i + 13] + 681279174
if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b
else a = bitOr(n * 16, n / 268435456) + b
n = bitXor(bitXor(a, b), c) + d + x[i] - 358537222
if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a
else d = bitOr(n * 2048, n / 2097152) + a
n = bitXor(bitXor(d, a), b) + c + x[i + 3] - 722521979
if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d
else c = bitOr(n * 65536, n / 65536) + d
n = bitXor(bitXor(c, d), a) + b + x[i + 6] + 76029189
if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c
else b = bitOr(n * 8388608, n / 512) + c
n = bitXor(bitXor(b, c), d) + a + x[i + 9] - 640364487
if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b
else a = bitOr(n * 16, n / 268435456) + b
n = bitXor(bitXor(a, b), c) + d + x[i + 12] - 421815835
if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a
else d = bitOr(n * 2048, n / 2097152) + a
n = bitXor(bitXor(d, a), b) + c + x[i + 15] + 530742520
if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d
else c = bitOr(n * 65536, n / 65536) + d
n = bitXor(bitXor(c, d), a) + b + x[i + 2] - 995338651
if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c
else b = bitOr(n * 8388608, n / 512) + c
 
-- Round(4) --
n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i] - 198630844
if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b
else a = bitOr(n * 64, n / 67108864) + b
n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 7] + 1126891415
if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a
else d = bitOr(n * 1024, n / 4194304) + a
n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 14] - 1416354905
if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d
else c = bitOr(n * 32768, n / 131072) + d
n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 5] - 57434055
if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c
else b = bitOr(n * 2097152, n / 2048) + c
n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i + 12] + 1700485571
if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b
else a = bitOr(n * 64, n / 67108864) + b
n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 3] - 1894986606
if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a
else d = bitOr(n * 1024, n / 4194304) + a
n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 10] - 1051523
if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d
else c = bitOr(n * 32768, n / 131072) + d
n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 1] - 2054922799
if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c
else b = bitOr(n * 2097152, n / 2048) + c
n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i + 8] + 1873313359
if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b
else a = bitOr(n * 64, n / 67108864) + b
n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 15] - 30611744
if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a
else d = bitOr(n * 1024, n / 4194304) + a
n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 6] - 1560198380
if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d
else c = bitOr(n * 32768, n / 131072) + d
n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 13] + 1309151649
if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c
else b = bitOr(n * 2097152, n / 2048) + c
n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i + 4] - 145523070
if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b
else a = bitOr(n * 64, n / 67108864) + b
n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 11] - 1120210379
if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a
else d = bitOr(n * 1024, n / 4194304) + a
n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 2] + 718787259
if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d
else c = bitOr(n * 32768, n / 131072) + d
n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 9] - 343485551
if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c
else b = bitOr(n * 2097152, n / 2048) + c
a = a + olda
b = b + oldb
c = c + oldc
d = d + oldd
i = i + 16
end repeat
 
t_iArr = [a, b, c, d]
ba = bytearray()
p = 1
repeat with i in t_iArr
if(i > 0) then
repeat with n = 1 to 4
ba[p] = (i mod 256)
i = i / 256
p = p+1
end repeat
else
i = bitNot(i)
repeat with n = 1 to 4
ba[p] = 255-(i mod 256)
i = i / 256
p = p+1
end repeat
end if
end repeat
ba.position = 1
return ba
end</syntaxhighlight>
 
<syntaxhighlight lang="lingo">tests = []
tests.add("")
tests.add("a")
tests.add("abc")
tests.add("message digest")
tests.add("abcdefghijklmnopqrstuvwxyz")
tests.add("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
tests.add("12345678901234567890123456789012345678901234567890123456789012345678901234567890")
repeat with t in tests
ba = md5(t)
put ba.toHexString(1, ba.length)
end repeat</syntaxhighlight>
 
{{out}}
<pre>
-- "d4 1d 8c d9 8f 00 b2 04 e9 80 09 98 ec f8 42 7e"
-- "0c c1 75 b9 c0 f1 b6 a8 31 c3 99 e2 69 77 26 61"
-- "90 01 50 98 3c d2 4f b0 d6 96 3f 7d 28 e1 7f 72"
-- "f9 6b 69 7d 7c b7 93 8d 52 5a 2f 31 aa f1 61 d0"
-- "c3 fc d3 d7 61 92 e4 00 7d fb 49 6c ca 67 e1 3b"
-- "d1 74 ab 98 d2 77 d9 f5 a5 61 1c 2c 9f 41 9d 9f"
-- "57 ed f4 a2 2b e3 c9 55 ac 49 da 2e 21 07 b6 7a"
</pre>
 
=={{header|Lua}}==
 
With advent of 5.3, Lua can now calculate a string representation of an md5 hash.
 
<syntaxhighlight lang="lua">-- shift amounts
local s = {
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
}
 
-- constants
local K = {
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
}
 
local function leftRotate(x, c)
return (x << c) | (x >> (32-c))
end
 
local function getInt(byteArray, n)
return (byteArray[n+3]<<24) + (byteArray[n+2]<<16) + (byteArray[n+1]<<8) + byteArray[n]
end
 
--- converts 32bit integer n to a little endian hex representation
-- @tparam integer n
local function lE(n)
local s = ''
for i = 0, 3 do
s = ('%s%02x'):format(s, (n>>(i*8))&0xff)
end
return s
end
 
--- md5
-- @tparam string message
local function md5(message)
local a0, b0, c0, d0 = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476
local bytes = {message:byte(1, -1)}
-- insert 1 bit (and the rest of the byte)
table.insert(bytes, 0x80)
 
-- pad with zeros until we have *just enough*
local p = #bytes%64
if p > 56 then
p = p - 64
end
for _ = p+1, 56 do
table.insert(bytes, 0)
end
 
-- insert the initial message length, in little-endian
local len = ((#message)<<3)&0xffffffffffffffff -- length in bits
for i = 0, 7 do
table.insert(bytes, (len>>(i*8))&0xff)
end
 
for i = 0, #bytes//64-1 do
local a, b, c, d = a0, b0, c0, d0
for j = 0, 63 do
local F, g
-- permutate
if j <= 15 then
F = (b & c) | (~b & d)
g = j
elseif j <= 31 then
F = (d & b) | (~d & c)
g = (5*j + 1) & 15
elseif j <= 47 then
F = b ~ c ~ d
g = (3*j + 5) & 15
else
F = c ~ (b | ~d)
g = (7*j) & 15
end
 
F = (F + a + K[j+1] + getInt(bytes, i*64+g*4+1))&0xffffffff
-- shuffle
a = d
d = c
c = b
b = (b + leftRotate(F, s[j+1]))&0xffffffff
end
-- update internal state
a0 = (a0 + a)&0xffffffff
b0 = (b0 + b)&0xffffffff
c0 = (c0 + c)&0xffffffff
d0 = (d0 + d)&0xffffffff
end
 
-- lua doesn't support any other byte strings. Could convert to a wacky string but this is more printable.
return lE(a0)..lE(b0)..lE(c0)..lE(d0)
end
 
local demo = {
[""] = "d41d8cd98f00b204e9800998ecf8427e",
["a"] = "0cc175b9c0f1b6a831c399e269772661",
["abc"] = "900150983cd24fb0d6963f7d28e17f72",
["message digest"] = "f96b697d7cb7938d525a2f31aaf161d0",
["abcdefghijklmnopqrstuvwxyz"] = "c3fcd3d76192e4007dfb496cca67e13b",
["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] = "d174ab98d277d9f5a5611c2c9f419d9f",
["12345678901234567890123456789012345678901234567890123456789012345678901234567890"] = "57edf4a22be3c955ac49da2e2107b67a",
}
 
for k, v in pairs(demo) do
local m = md5(k)
print(("%s [%2s] <== \"%s\""):format(m, m==v and 'OK' or '', k))
end</syntaxhighlight>
 
Output:
<syntaxhighlight lang="lua">f96b697d7cb7938d525a2f31aaf161d0 [OK] <== "message digest"
d174ab98d277d9f5a5611c2c9f419d9f [OK] <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
c3fcd3d76192e4007dfb496cca67e13b [OK] <== "abcdefghijklmnopqrstuvwxyz"
d41d8cd98f00b204e9800998ecf8427e [OK] <== ""
900150983cd24fb0d6963f7d28e17f72 [OK] <== "abc"
57edf4a22be3c955ac49da2e2107b67a [OK] <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
0cc175b9c0f1b6a831c399e269772661 [OK] <== "a"
</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">md5[string_String] :=
Module[{r = {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17,
22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4,
Line 1,694 ⟶ 3,545:
FromDigits[
Flatten[Reverse@IntegerDigits[#, 256, 4] & /@ {h0, h1, h2, h3}],
256], 16, 32]]</syntaxhighlight>
</lang>
Example:
<langsyntaxhighlight Mathematicalang="mathematica">md5["12345678901234567890123456789012345678901234567890123456789012345678901234567890"]</langsyntaxhighlight>
Output:
<syntaxhighlight lang Mathematica="mathematica">0x57edf4a22be3c955ac49da2e2107b67a</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 1,706 ⟶ 3,556:
=={{header|Modula-3}}==
 
<langsyntaxhighlight lang="modula3">INTERFACE MD5;
 
IMPORT Word;
Line 1,724 ⟶ 3,574:
PROCEDURE ToText(hash: Digest): TEXT;
 
END MD5.</langsyntaxhighlight>
<langsyntaxhighlight lang="modula3">MODULE MD5;
 
IMPORT Word, Text, Fmt;
Line 1,968 ⟶ 3,818:
 
BEGIN
END MD5.</langsyntaxhighlight>
Example usage:
<langsyntaxhighlight lang="modula3">MODULE Main;
 
IMPORT MD5, IO;
Line 1,980 ⟶ 3,830:
MD5.Update(md5ctx, "The quick brown fox jumped over the lazy dog's back");
IO.Put(MD5.ToText(MD5.Final(md5ctx)) & "\n");
END Main.</langsyntaxhighlight>
Output:
<pre>
Line 1,986 ⟶ 3,836:
</pre>
 
=={{header|Perl 6Nim}}==
<syntaxhighlight lang="nim">import sequtils
 
const
<lang perl6>use Test;
ChunkSize = 512 div 8
SumSize = 128 div 8
 
proc extractChunk(msg : seq[uint8], chunk: var openarray[uint32], offset: int) =
sub prefix:<¬>(\x) { (+^ x) % 2**32 }
var
sub infix:<⊞>(\x, \y) { (x + y) % 2**32 }
srcIndex = offset
sub infix:«<<<»(\x, \n) { (x +< n) % 2**32 +| (x +> (32-n)) }
 
for dstIndex in 0 ..< 16:
constant FGHI = -> \X, \Y, \Z { (X +& Y) +| (¬X +& Z) },
chunk[dstIndex] = 0
-> \X, \Y, \Z { (X +& Z) +| (Y +& ¬Z) },
for ii in 0 ..< 4:
-> \X, \Y, \Z { X +^ Y +^ Z },
chunk[dstIndex] = chunk[dstIndex] shr 8
-> \X, \Y, \Z { Y +^ (X +| ¬Z) };
chunk[dstIndex] = chunk[dstIndex] or (msg[srcIndex].uint32 shl 24)
srcIndex.inc
 
proc leftRotate(val: uint32, shift: int) : uint32 =
constant S = (7, 12, 17, 22) xx 4,
result = (val shl shift) or (val shr (5,32 - 9, 14, 20shift)) xx 4,
(4, 11, 16, 23) xx 4,
proc md5Sum(msg : seq[uint8]) : array[SumSize, uint8] =
(6, 10, 15, 21) xx 4;
const
s : array[ChunkSize, int] =
[ 7, 12, 17, 22, 7, 12, 17, 22,
7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20,
5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23,
4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21,
6, 10, 15, 21, 6, 10, 15, 21 ]
 
K : array[ChunkSize, uint32] =
constant T = (floor(abs(sin($_ + 1)) * 2**32) for ^64);
[ 0xd76aa478'u32, 0xe8c7b756'u32, 0x242070db'u32, 0xc1bdceee'u32,
0xf57c0faf'u32, 0x4787c62a'u32, 0xa8304613'u32, 0xfd469501'u32,
0x698098d8'u32, 0x8b44f7af'u32, 0xffff5bb1'u32, 0x895cd7be'u32,
0x6b901122'u32, 0xfd987193'u32, 0xa679438e'u32, 0x49b40821'u32,
0xf61e2562'u32, 0xc040b340'u32, 0x265e5a51'u32, 0xe9b6c7aa'u32,
0xd62f105d'u32, 0x02441453'u32, 0xd8a1e681'u32, 0xe7d3fbc8'u32,
0x21e1cde6'u32, 0xc33707d6'u32, 0xf4d50d87'u32, 0x455a14ed'u32,
0xa9e3e905'u32, 0xfcefa3f8'u32, 0x676f02d9'u32, 0x8d2a4c8a'u32,
0xfffa3942'u32, 0x8771f681'u32, 0x6d9d6122'u32, 0xfde5380c'u32,
0xa4beea44'u32, 0x4bdecfa9'u32, 0xf6bb4b60'u32, 0xbebfbc70'u32,
0x289b7ec6'u32, 0xeaa127fa'u32, 0xd4ef3085'u32, 0x04881d05'u32,
0xd9d4d039'u32, 0xe6db99e5'u32, 0x1fa27cf8'u32, 0xc4ac5665'u32,
0xf4292244'u32, 0x432aff97'u32, 0xab9423a7'u32, 0xfc93a039'u32,
0x655b59c3'u32, 0x8f0ccc92'u32, 0xffeff47d'u32, 0x85845dd1'u32,
0x6fa87e4f'u32, 0xfe2ce6e0'u32, 0xa3014314'u32, 0x4e0811a1'u32,
0xf7537e82'u32, 0xbd3af235'u32, 0x2ad7d2bb'u32, 0xeb86d391'u32 ]
 
constant k = ( $_ for ^16),
((5*$_ + 1) % 16 for ^16),
((3*$_ + 5) % 16 for ^16),
((7*$_ ) % 16 for ^16);
 
# Pad with 1-bit, and fill with 0's up to 448 bits mod 512
sub little-endian($w, $n, *@v) { (@v X+> ($w X* ^$n)) X% (2 ** $w) }
var paddedMsgSize = msg.len + 1
var remain = (msg.len + 1) mod ChunkSize
if remain > (448 div 8):
paddedMsgSize += ChunkSize - remain + (448 div 8)
else:
paddedMsgSize += (448 div 8) - remain
 
var paddingSize = paddedMsgSize - msg.len
sub md5-pad(Blob $msg)
var padding = newSeq[uint8](paddingSize)
{
padding[0] = 0x80
my \bits = 8 * $msg.elems;
 
my @padded = $msg.list, 0x80, 0x00 xx (-(bits div 8 + 1 + 8) % 64);
# Pad @padded.map({with :256[$^d,$^c,$^b,$^a]number of })*bits* in original message, little-endian(32, 2, bits);
var sizePadding = newSeq[uint8](8)
var size = msg.len * 8
for ii in 0 ..< 4:
sizePadding[ii] = uint8(size and 0xff)
size = size shr 8
 
var paddedMsg = concat(msg, padding, sizePadding)
 
var accum = [ 0x67452301'u32, 0xefcdab89'u32, 0x98badcfe'u32, 0x10325476'u32 ]
 
for offset in countup(0, paddedMsg.len - 1, ChunkSize):
var A = accum[0]
var B = accum[1]
var C = accum[2]
var D = accum[3]
var F : uint32
var g : int
var M : array[16, uint32]
var dTemp : uint32
 
extractChunk(paddedMsg, M, offset)
 
# This is pretty much the same as Wikipedia's MD5 entry
for ii in 0 .. 63:
if ii <= 15:
F = (B and C) or ((not B) and D)
g = ii
 
elif ii <= 31:
F = (D and B) or ((not D) and C)
g = (5 * ii + 1) mod 16
 
elif ii <= 47:
F = B xor C xor D
g = (3 * ii + 5) mod 16
 
else:
F = C xor (B or (not D))
g = (7 * ii) mod 16
dTemp = D
D = C
C = B
B = B + leftRotate((A + F + K[ii] + M[g]), s[ii])
A = dTemp
 
accum[0] += A
accum[1] += B
accum[2] += C
accum[3] += D
 
# Convert four 32-bit accumulators to 16 byte array, little-endian
var dstIdx : int
for acc in accum:
var tmp = acc
 
for ii in 0 ..< 4:
result[dstIdx] = uint8(tmp and 0xff)
tmp = tmp shr 8
dstIdx.inc
 
# Only needed to convert from string to uint8 sequence
iterator items * (str : string) : uint8 =
for ii in 0 ..< len(str):
yield str[ii].uint8
 
proc main =
var msg = ""
var sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0xD4'u8, 0x1D, 0x8C, 0xD9, 0x8F, 0x00, 0xB2, 0x04,
0xE9, 0x80, 0x09, 0x98, 0xEC, 0xF8, 0x42, 0x7E ] )
 
msg = "The quick brown fox jumps over the lazy dog"
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0x9E'u8, 0x10, 0x7D, 0x9D, 0x37, 0x2B, 0xB6, 0x82,
0x6B, 0xD8, 0x1D, 0x35, 0x42, 0xA4, 0x19, 0xD6 ] )
 
msg = "The quick brown fox jumps over the lazy dog."
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0xE4'u8, 0xD9, 0x09, 0xC2, 0x90, 0xD0, 0xFB, 0x1C,
0xA0, 0x68, 0xFF, 0xAD, 0xDF, 0x22, 0xCB, 0xD0 ])
 
 
# Message size around magic 512 bits
msg = "01234567890123456789012345678901234567890123456789012345678901234"
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0xBE'u8, 0xB9, 0xF4, 0x8B, 0xC8, 0x02, 0xCA, 0x5C,
0xA0, 0x43, 0xBC, 0xC1, 0x5E, 0x21, 0x9A, 0x5A ])
 
msg = "0123456789012345678901234567890123456789012345678901234567890123"
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0x7F'u8, 0x7B, 0xFD, 0x34, 0x87, 0x09, 0xDE, 0xEA,
0xAC, 0xE1, 0x9E, 0x3F, 0x53, 0x5F, 0x8C, 0x54 ])
 
msg = "012345678901234567890123456789012345678901234567890123456789012"
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0xC5'u8, 0xE2, 0x56, 0x43, 0x7E, 0x75, 0x80, 0x92,
0xDB, 0xFE, 0x06, 0x28, 0x3E, 0x48, 0x90, 0x19 ])
 
 
# Message size around magic 448 bits
msg = "01234567890123456789012345678901234567890123456789012345"
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0x8A'u8, 0xF2, 0x70, 0xB2, 0x84, 0x76, 0x10, 0xE7,
0x42, 0xB0, 0x79, 0x1B, 0x53, 0x64, 0x8C, 0x09 ])
 
msg = "0123456789012345678901234567890123456789012345678901234"
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0x6E'u8, 0x7A, 0x4F, 0xC9, 0x2E, 0xB1, 0xC3, 0xF6,
0xE6, 0x52, 0x42, 0x5B, 0xCC, 0x8D, 0x44, 0xB5 ])
 
msg = "012345678901234567890123456789012345678901234567890123"
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0x3D'u8, 0xFF, 0x83, 0xC8, 0xFA, 0xDD, 0x26, 0x37,
0x0D, 0x5B, 0x09, 0x84, 0x09, 0x64, 0x44, 0x57 ])
 
main()</syntaxhighlight>
 
=={{header|ooRexx}}==
{{works with|ooRexx|4.2.0 (and later)}}
<syntaxhighlight lang="oorexx">
#!/usr/bin/env rexx
 
/* Expected results:
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
*/
 
md5 = .md5~new; md5~update(""); say md5~digest
md5 = .md5~new; md5~update("a"); say md5~digest
md5 = .md5~new; md5~update("abc"); say md5~digest
md5 = .md5~new; md5~update("message digest"); say md5~digest
md5 = .md5~new("abcdefghijklmnopqrstuvwxyz"); say md5~digest
md5 = .md5~new("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); md5~update("abcdefghijklmnopqrstuvwxyz0123456789"); say md5~digest
md5 = .md5~new; md5~update("12345678901234567890123456789012345678901234567890123456789012345678901234567890"); say md5~digest
 
-- requires OORexx 4.2.0 or later
-- standard numeric digits of 9 is not enough in this case
::options digits 20
 
-- Implementation mainly based on pseudocode in https://en.wikipedia.org/wiki/MD5
::class md5 public
 
::method init
expose a0 b0 c0 d0 count buffer index K. s -- instance variables
use strict arg chunk=""
-- Initialize message digest
a0 = .int32~new('67452301'x,"C") -- A
b0 = .int32~new('efcdab89'x,"C") -- B
c0 = .int32~new('98badcfe'x,"C") -- C
d0 = .int32~new('10325476'x,"C") -- D
-- The 512 bit chunk buffer
buffer = .mutablebuffer~new('00'x~copies(64),64)
-- The position in the buffer to insert new input
index = 1
-- message bytecount
count = 0
-- initialize leftrotate amounts
nrs = .array~of(7,12,17,22)
s = nrs~union(nrs)~union(nrs)~union(nrs)
nrs = .array~of(5,9,14,20)
s = s~union(nrs)~union(nrs)~union(nrs)~union(nrs)
nrs = .array~of(4,11,16,23)
s = s~union(nrs)~union(nrs)~union(nrs)~union(nrs)
nrs = .array~of(6,10,15,21)
s = s~union(nrs)~union(nrs)~union(nrs)~union(nrs)
-- initialize sinus derived constants.
-- sin function from RXMath Library shipped with OORexx
-- see ::routine directive at the end of the code
do i=0 to 63
K.i = .int32~new(((2**32)*(sin(i+1,16,R)~abs))~floor)
end
-- process initial string if any
self~update(chunk)
exit
 
::method update
expose a0 b0 c0 d0 count buffer index K. s -- instance variables
use strict arg chunk
count += chunk~length
if chunk~length<65-index then do
buffer~overlay(chunk,index)
index += chunk~length
end
else do
split = 65-index+1
parse var chunk part =(split) chunk
buffer~overlay(part,index)
index = 65
end
-- Only process completely filled buffer
do while index=65
A = a0
B = b0
C = c0
D = d0
do i=0 to 63
select
when i<16 then do
F = D~xor(B~and(C~xor(D)))
g = i
end
when i<32 then do
F = C~xor(D~and(B~xor(C)))
g = (5*i+1)//16
end
when i<48 then do
F = B~xor(C)~xor(D)
g = (3*i+5)//16
end
otherwise do
F = C~xor(B~or(D~xor(.int32~new('ffffffff'x,"C"))))
g = (7*i)//16
end
end
M = .int32~new(buffer~substr(g*4+1,4)~reverse,"C") -- 32bit word in little-endian
dTemp = D
D = C
C = B
B = (B + (A+F+K.i+M)~bitrotate(s[i+1]))
A = dTemp
end
a0 = a0+A
b0 = b0+B
c0 = c0+C
d0 = d0+D
parse var chunk part 65 chunk
index = part~length+1
buffer~overlay(part,1,part~length)
end
exit
 
::method digest
expose a0 b0 c0 d0 count buffer index K s -- instance variables
padlen = 64
if index<57 then padlen = 57-index
if index>57 then padlen = 121-index
padding = '00'x~copies(padlen)~bitor('80'x)
bitcount = count*8//2**64
lowword = bitcount//2**32
hiword = bitcount%2**32
lowcount = lowword~d2c(4)~reverse -- make it little-endian
hicount = hiword~d2c(4)~reverse -- make it little-endian
self~update(padding || lowcount || hicount)
return a0~string || b0~string || c0~string || d0~string
 
-- A convenience class to encapsulate operations on non OORexx-like
-- things such as little-endian 32-bit words
::class int32 public
 
::attribute arch class
 
::method init class
self~arch = "little-endian" -- can be adapted for multiple architectures
 
-- Method to create an int32 like object
-- Input can be a OORexx whole number (type="I") or
-- a character string of 4 bytes (type="C")
-- input truncated or padded to 32-bit word/string
::method init
expose char4 int32
use strict arg input, type="Integer"
-- type must be one of "I"nteger or "C"haracter
t = type~subchar(1)~upper
select
when t=='I' then do
char4 = input~d2c(4)
int32 = char4~c2d
end
when t=='C' then do
char4 = input~right(4,'00'x)
int32 = char4~c2d
end
otherwise do
raise syntax 93.915 array("IC",type)
end
end
exit
 
::method xor -- wrapper for OORexx bitxor method
expose char4
use strict arg other
return .int32~new(char4~bitxor(other~char),"C")
::method and -- wrapper for OORexx bitand method
expose char4
use strict arg other
return .int32~new(char4~bitand(other~char),"C")
::method or -- wrapper for OORexx bitor method
expose char4
use strict arg other
return .int32~new(char4~bitor(other~char),"C")
::method bitleft -- OORexx shift (<<) implementation
expose char4
use strict arg bits
bstring = char4~c2x~x2b
bstring = bstring~substr(bits+1)~left(bstring~length,'0')
return .int32~new(bstring~b2x~x2d)
 
-- For those who like to code the shift operation in a traditional way
::method '<<'
forward to (self) message("bitleft")
 
::method bitright -- OORexx shift (>>) implementation
expose char4
use strict arg bits, signed=.false
bstring = char4~c2x~x2b
fill = '0'
if signed then fill = bstring~subchar(1)
bstring = bstring~left(bstring~length-bits)~right(bstring~length,fill)
return .int32~new(bstring~b2x~x2d)
 
-- For those who like to code the shift operation in a traditional way
::method '>>'
forward to (self) message("bitright")
 
::method bitnot -- OORexx not implementation
expose char4
return .int32~new(char4~bitxor('ffffffff'x)~c2d,"C")
 
::method bitrotate -- OORexx (left) rotate method
expose char4
use strict arg bits, direction='left'
d = direction~subchar(1)~upper
if d=='L' then do
leftpart = self~bitleft(bits)
rightpart = self~bitright(32-bits)
end
else do
leftpart = self~bitleft(32-bits)
rightpart = self~bitright(bits)
end
return rightpart~or(leftpart)
 
::method int -- retrieve integer as number
expose int32
return int32
 
::method char -- retrieve integer as characters
expose char4
return char4
 
::method '+' -- OORexx method to add 2 .int32 instances
expose int32
use strict arg other
return .int32~new(int32+other~int)
 
::method string -- retrieve integer as hexadecimal string
expose char4
return char4~reverse~c2x~lower
-- Simplify function names for the necessary 'RxMath' functions
::routine sin EXTERNAL "LIBRARY rxmath RxCalcSin"
</syntaxhighlight>
 
=={{header|Perl}}==
{{works with|Perl|5.10.1 (and later)}}
<syntaxhighlight lang="perl">use strict;
use warnings;
use integer;
use Test::More;
 
BEGIN { plan tests => 7 }
 
sub A() { 0x67_45_23_01 }
sub B() { 0xef_cd_ab_89 }
sub C() { 0x98_ba_dc_fe }
sub D() { 0x10_32_54_76 }
sub MAX() { 0xFFFFFFFF }
 
sub padding {
my $l = length (my $msg = shift() . chr(128));
$msg .= "\0" x (($l%64<=56?56:120)-$l%64);
$l = ($l-1)*8;
$msg .= pack 'VV', $l & MAX , ($l >> 16 >> 16);
}
 
sub rotate_left {
sub md5-block(@H is rw, @X)
($_[0] << $_[1]) | (( $_[0] >> (32 - $_[1]) ) & ((1 << $_[1]) - 1));
{
}
my ($A, $B, $C, $D) = @H;
 
for ^64 -> \i {
sub gen_code {
my \f = FGHI[i div 16]($B, $C, $D);
# Discard upper 32 bits on 64 bit archs.
($A, $B, $C, $D)
my $MSK = ($D,(1 $B<< 16) (($A<< 16) f? ' T[i]& ' @X[k[i]]). <<<MAX S[i]),: $B, $C)'';
my %f = (
FF => "X0=rotate_left((X3^(X1&(X2^X3)))+X0+X4+X6$MSK,X5)+X1$MSK;",
GG => "X0=rotate_left((X2^(X3&(X1^X2)))+X0+X4+X6$MSK,X5)+X1$MSK;",
HH => "X0=rotate_left((X1^X2^X3)+X0+X4+X6$MSK,X5)+X1$MSK;",
II => "X0=rotate_left((X2^(X1|(~X3)))+X0+X4+X6$MSK,X5)+X1$MSK;",
);
 
my %s = ( # shift lengths
S11 => 7, S12 => 12, S13 => 17, S14 => 22, S21 => 5, S22 => 9, S23 => 14,
S24 => 20, S31 => 4, S32 => 11, S33 => 16, S34 => 23, S41 => 6, S42 => 10,
S43 => 15, S44 => 21
);
 
my $insert = "\n";
while(defined( my $data = <DATA> )) {
chomp $data;
next unless $data =~ /^[FGHI]/;
my ($func,@x) = split /,/, $data;
my $c = $f{$func};
$c =~ s/X(\d)/$x[$1]/g;
$c =~ s/(S\d{2})/$s{$1}/;
$c =~ s/^(.*)=rotate_left\((.*),(.*)\)\+(.*)$//;
 
my $su = 32 - $3;
my $sh = (1 << $3) - 1;
 
$c = "$1=(((\$r=$2)<<$3)|((\$r>>$su)&$sh))+$4";
 
$insert .= "\t$c\n";
}
close DATA;
 
my $dump = '
sub round {
my ($a,$b,$c,$d) = @_[0 .. 3];
my $r;' . $insert . '
$_[0]+$a' . $MSK . ', $_[1]+$b ' . $MSK .
', $_[2]+$c' . $MSK . ', $_[3]+$d' . $MSK . ';
}';
eval $dump;
}
 
gen_code();
 
sub _encode_hex { unpack 'H*', $_[0] }
 
sub md5 {
my $message = padding(join'',@_);
my ($a,$b,$c,$d) = (A,B,C,D);
my $i;
for $i (0 .. (length $message)/64-1) {
my @X = unpack 'V16', substr $message,$i*64,64;
($a,$b,$c,$d) = round($a,$b,$c,$d,@X);
}
@Hpack «⊞=» ('V4',$Aa, $Bb, $Cc, $D)d;
}
 
my $strings = {
sub md5(Blob $msg --> Blob)
'd41d8cd98f00b204e9800998ecf8427e' => '',
{
'0cc175b9c0f1b6a831c399e269772661' => 'a',
my @M = md5-pad($msg);
'900150983cd24fb0d6963f7d28e17f72' => 'abc',
my @H = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476;
'f96b697d7cb7938d525a2f31aaf161d0' => 'message digest',
md5-block(@H, @M[$_ .. $_+15]) for 0, 16 ...^ +@M;
'c3fcd3d76192e4007dfb496cca67e13b' => 'abcdefghijklmnopqrstuvwxyz',
Blob.new: little-endian(8, 4, @H);
'd174ab98d277d9f5a5611c2c9f419d9f' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
'57edf4a22be3c955ac49da2e2107b67a' => '12345678901234567890123456789012345678901234567890123456789012345678901234567890',
};
 
for my $k (keys %$strings) {
my $digest = _encode_hex md5($strings->{$k});
is($digest, $k, "$digest is MD5 digest $strings->{$k}");
}
 
__DATA__
for 'd41d8cd98f00b204e9800998ecf8427e', '',
FF,$a,$b,$c,$d,$_[4],7,0xd76aa478,/* 1 */
'0cc175b9c0f1b6a831c399e269772661', 'a',
FF,$d,$a,$b,$c,$_[5],12,0xe8c7b756,/* 2 */
'900150983cd24fb0d6963f7d28e17f72', 'abc',
FF,$c,$d,$a,$b,$_[6],17,0x242070db,/* 3 */
'f96b697d7cb7938d525a2f31aaf161d0', 'message digest',
FF,$b,$c,$d,$a,$_[7],22,0xc1bdceee,/* 4 */
'c3fcd3d76192e4007dfb496cca67e13b', 'abcdefghijklmnopqrstuvwxyz',
FF,$a,$b,$c,$d,$_[8],7,0xf57c0faf,/* 5 */
'd174ab98d277d9f5a5611c2c9f419d9f', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
FF,$d,$a,$b,$c,$_[9],12,0x4787c62a,/* 6 */
'57edf4a22be3c955ac49da2e2107b67a', '12345678901234567890123456789012345678901234567890123456789012345678901234567890'
FF,$c,$d,$a,$b,$_[10],17,0xa8304613,/* 7 */
-> $expected, $msg {
FF,$b,$c,$d,$a,$_[11],22,0xfd469501,/* 8 */
my $digest = md5($msg.encode('ascii')).list».fmt('%02x').join;
FF,$a,$b,$c,$d,$_[12],7,0x698098d8,/* 9 */
is($digest, $expected, "$digest is MD5 digest of '$msg'");
FF,$d,$a,$b,$c,$_[13],12,0x8b44f7af,/* 10 */
}</lang>
FF,$c,$d,$a,$b,$_[14],17,0xffff5bb1,/* 11 */
FF,$b,$c,$d,$a,$_[15],22,0x895cd7be,/* 12 */
FF,$a,$b,$c,$d,$_[16],7,0x6b901122,/* 13 */
FF,$d,$a,$b,$c,$_[17],12,0xfd987193,/* 14 */
FF,$c,$d,$a,$b,$_[18],17,0xa679438e,/* 15 */
FF,$b,$c,$d,$a,$_[19],22,0x49b40821,/* 16 */
GG,$a,$b,$c,$d,$_[5],5,0xf61e2562,/* 17 */
GG,$d,$a,$b,$c,$_[10],9,0xc040b340,/* 18 */
GG,$c,$d,$a,$b,$_[15],14,0x265e5a51,/* 19 */
GG,$b,$c,$d,$a,$_[4],20,0xe9b6c7aa,/* 20 */
GG,$a,$b,$c,$d,$_[9],5,0xd62f105d,/* 21 */
GG,$d,$a,$b,$c,$_[14],9,0x2441453,/* 22 */
GG,$c,$d,$a,$b,$_[19],14,0xd8a1e681,/* 23 */
GG,$b,$c,$d,$a,$_[8],20,0xe7d3fbc8,/* 24 */
GG,$a,$b,$c,$d,$_[13],5,0x21e1cde6,/* 25 */
GG,$d,$a,$b,$c,$_[18],9,0xc33707d6,/* 26 */
GG,$c,$d,$a,$b,$_[7],14,0xf4d50d87,/* 27 */
GG,$b,$c,$d,$a,$_[12],20,0x455a14ed,/* 28 */
GG,$a,$b,$c,$d,$_[17],5,0xa9e3e905,/* 29 */
GG,$d,$a,$b,$c,$_[6],9,0xfcefa3f8,/* 30 */
GG,$c,$d,$a,$b,$_[11],14,0x676f02d9,/* 31 */
GG,$b,$c,$d,$a,$_[16],20,0x8d2a4c8a,/* 32 */
HH,$a,$b,$c,$d,$_[9],4,0xfffa3942,/* 33 */
HH,$d,$a,$b,$c,$_[12],11,0x8771f681,/* 34 */
HH,$c,$d,$a,$b,$_[15],16,0x6d9d6122,/* 35 */
HH,$b,$c,$d,$a,$_[18],23,0xfde5380c,/* 36 */
HH,$a,$b,$c,$d,$_[5],4,0xa4beea44,/* 37 */
HH,$d,$a,$b,$c,$_[8],11,0x4bdecfa9,/* 38 */
HH,$c,$d,$a,$b,$_[11],16,0xf6bb4b60,/* 39 */
HH,$b,$c,$d,$a,$_[14],23,0xbebfbc70,/* 40 */
HH,$a,$b,$c,$d,$_[17],4,0x289b7ec6,/* 41 */
HH,$d,$a,$b,$c,$_[4],11,0xeaa127fa,/* 42 */
HH,$c,$d,$a,$b,$_[7],16,0xd4ef3085,/* 43 */
HH,$b,$c,$d,$a,$_[10],23,0x4881d05,/* 44 */
HH,$a,$b,$c,$d,$_[13],4,0xd9d4d039,/* 45 */
HH,$d,$a,$b,$c,$_[16],11,0xe6db99e5,/* 46 */
HH,$c,$d,$a,$b,$_[19],16,0x1fa27cf8,/* 47 */
HH,$b,$c,$d,$a,$_[6],23,0xc4ac5665,/* 48 */
II,$a,$b,$c,$d,$_[4],6,0xf4292244,/* 49 */
II,$d,$a,$b,$c,$_[11],10,0x432aff97,/* 50 */
II,$c,$d,$a,$b,$_[18],15,0xab9423a7,/* 51 */
II,$b,$c,$d,$a,$_[9],21,0xfc93a039,/* 52 */
II,$a,$b,$c,$d,$_[16],6,0x655b59c3,/* 53 */
II,$d,$a,$b,$c,$_[7],10,0x8f0ccc92,/* 54 */
II,$c,$d,$a,$b,$_[14],15,0xffeff47d,/* 55 */
II,$b,$c,$d,$a,$_[5],21,0x85845dd1,/* 56 */
II,$a,$b,$c,$d,$_[12],6,0x6fa87e4f,/* 57 */
II,$d,$a,$b,$c,$_[19],10,0xfe2ce6e0,/* 58 */
II,$c,$d,$a,$b,$_[10],15,0xa3014314,/* 59 */
II,$b,$c,$d,$a,$_[17],21,0x4e0811a1,/* 60 */
II,$a,$b,$c,$d,$_[8],6,0xf7537e82,/* 61 */
II,$d,$a,$b,$c,$_[15],10,0xbd3af235,/* 62 */
II,$c,$d,$a,$b,$_[6],15,0x2ad7d2bb,/* 63 */
II,$b,$c,$d,$a,$_[13],21,0xeb86d391,/* 64 */</syntaxhighlight>
 
{{out}}
<pre>
<pre>ok 1 - d41d8cd98f00b204e9800998ecf8427e is MD5 digest of ''
1..7
ok 2 - 0cc175b9c0f1b6a831c399e269772661 is MD5 digest of 'a'
ok 31 - 900150983cd24fb0d6963f7d28e17f72c3fcd3d76192e4007dfb496cca67e13b is MD5 digest of 'abc'abcdefghijklmnopqrstuvwxyz
ok 42 - f96b697d7cb7938d525a2f31aaf161d0 is MD5 digest of 'message digest'
ok 53 - c3fcd3d76192e4007dfb496cca67e13b900150983cd24fb0d6963f7d28e17f72 is MD5 digest of 'abcdefghijklmnopqrstuvwxyz'abc
ok 4 - d41d8cd98f00b204e9800998ecf8427e is MD5 digest
ok 6 - d174ab98d277d9f5a5611c2c9f419d9f is MD5 digest of 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
ok 75 - 57edf4a22be3c955ac49da2e2107b67a is MD5 digest of '12345678901234567890123456789012345678901234567890123456789012345678901234567890'</pre>
ok 6 - 0cc175b9c0f1b6a831c399e269772661 is MD5 digest a
ok 7 - d174ab98d277d9f5a5611c2c9f419d9f is MD5 digest ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
</pre>
 
=={{header|Phix}}==
Non-optimised. Originally written by Davi Tassinari de Figueiredo.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\md5.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">uxor</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">data1</span><span style="color: #0000FF;">,</span><span style="color: #004080;">atom</span> <span style="color: #000000;">data2</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">result</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">data1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">data2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">result</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000000;">result</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">#100000000</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">result</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">uor</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">data1</span><span style="color: #0000FF;">,</span><span style="color: #004080;">atom</span> <span style="color: #000000;">data2</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">result</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">or_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">data1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">data2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">result</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000000;">result</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">#100000000</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">result</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#100000000</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">word</span><span style="color: #0000FF;">,</span><span style="color: #004080;">integer</span> <span style="color: #000000;">bits</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- left rotate the bits of a 32-bit number by the specified number of bits</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">*</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bits</span><span style="color: #0000FF;">))+</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">/</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">32</span><span style="color: #0000FF;">-</span><span style="color: #000000;">bits</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">K</span> <span style="color: #0000FF;">=</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">#d76aa478</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#e8c7b756</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#242070db</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#c1bdceee</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#f57c0faf</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#4787c62a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#a8304613</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#fd469501</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">#698098d8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#8b44f7af</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#ffff5bb1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#895cd7be</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#6b901122</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#fd987193</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#a679438e</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#49b40821</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">#f61e2562</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#c040b340</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#265e5a51</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#e9b6c7aa</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#d62f105d</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#02441453</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#d8a1e681</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#e7d3fbc8</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">#21e1cde6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#c33707d6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#f4d50d87</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#455a14ed</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#a9e3e905</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#fcefa3f8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#676f02d9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#8d2a4c8a</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">#fffa3942</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#8771f681</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#6d9d6122</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#fde5380c</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#a4beea44</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#4bdecfa9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#f6bb4b60</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#bebfbc70</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">#289b7ec6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#eaa127fa</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#d4ef3085</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#04881d05</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#d9d4d039</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#e6db99e5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#1fa27cf8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#c4ac5665</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">#f4292244</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#432aff97</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#ab9423a7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#fc93a039</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#655b59c3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#8f0ccc92</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#ffeff47d</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#85845dd1</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">#6fa87e4f</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#fe2ce6e0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#a3014314</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#4e0811a1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#f7537e82</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#bd3af235</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#2ad7d2bb</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#eb86d391</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">m_block</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">,</span><span style="color: #000000;">14</span><span style="color: #0000FF;">,</span><span style="color: #000000;">15</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">15</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">14</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12</span><span style="color: #0000FF;">,</span><span style="color: #000000;">15</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">14</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">15</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">11</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">14</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">c_words</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">#67452301</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#efcdab89</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#98badcfe</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#10325476</span><span style="color: #0000FF;">}</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">words</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">divide_in_words</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">message</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- Divides the string into words (32-bit numbers)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">message</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">l</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">word</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">l</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">word</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">bytes_to_int</span><span style="color: #0000FF;">(</span><span style="color: #000000;">message</span><span style="color: #0000FF;">[</span><span style="color: #000000;">word</span><span style="color: #0000FF;">*</span><span style="color: #000000;">4</span><span style="color: #0000FF;">-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">..</span><span style="color: #000000;">word</span><span style="color: #0000FF;">*</span><span style="color: #000000;">4</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">process_block</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">block</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- Updates the words according to the contents of the block</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span>
<span style="color: #000000;">block</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">divide_in_words</span><span style="color: #0000FF;">(</span><span style="color: #000000;">block</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">]</span>
<span style="color: #000080;font-style:italic;">-- Round 1</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">step</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">16</span> <span style="color: #008080;">by</span> <span style="color: #000000;">4</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span> <span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span> <span style="color: #0000FF;">]+</span><span style="color: #000000;">uor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">not_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">),</span><span style="color: #000000;">d</span><span style="color: #0000FF;">))),</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">uor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">not_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">),</span><span style="color: #000000;">c</span><span style="color: #0000FF;">))),</span><span style="color: #000000;">12</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">uor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">not_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">),</span><span style="color: #000000;">b</span><span style="color: #0000FF;">))),</span><span style="color: #000000;">17</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">uor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">not_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">),</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))),</span><span style="color: #000000;">22</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- Round 2</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">step</span><span style="color: #0000FF;">=</span><span style="color: #000000;">17</span> <span style="color: #008080;">to</span> <span style="color: #000000;">32</span> <span style="color: #008080;">by</span> <span style="color: #000000;">4</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span> <span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span> <span style="color: #0000FF;">]+</span><span style="color: #000000;">uor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">not_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)))),</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">uor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">not_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)))),</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">uor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">not_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)))),</span><span style="color: #000000;">14</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">uor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">not_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)))),</span><span style="color: #000000;">20</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- Round 3</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">step</span><span style="color: #0000FF;">=</span><span style="color: #000000;">33</span> <span style="color: #008080;">to</span> <span style="color: #000000;">48</span> <span style="color: #008080;">by</span> <span style="color: #000000;">4</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span> <span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span> <span style="color: #0000FF;">]+</span><span style="color: #000000;">uxor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">))),</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">uxor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">))),</span><span style="color: #000000;">11</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">uxor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">))),</span><span style="color: #000000;">16</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">uxor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))),</span><span style="color: #000000;">23</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- Round 4</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">step</span><span style="color: #0000FF;">=</span><span style="color: #000000;">49</span> <span style="color: #008080;">to</span> <span style="color: #000000;">64</span> <span style="color: #008080;">by</span> <span style="color: #000000;">4</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span> <span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span> <span style="color: #0000FF;">]+</span><span style="color: #000000;">uxor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">or_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">not_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)))),</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">uxor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">or_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">not_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)))),</span><span style="color: #000000;">10</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">uxor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">or_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">not_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)))),</span><span style="color: #000000;">15</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">+</span><span style="color: #000000;">rol</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">+</span><span style="color: #000000;">block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m_block</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]]+</span><span style="color: #000000;">K</span><span style="color: #0000FF;">[</span><span style="color: #000000;">step</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">uxor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">or_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">not_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)))),</span><span style="color: #000000;">21</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- Update the words</span>
<span style="color: #000000;">words</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">pad_message</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">message</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- Add bytes to the end of the message so it can be divided
-- in an exact number of 64-byte blocks.</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">message</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">bytes_to_add</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">64</span><span style="color: #0000FF;">-</span><span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">l</span><span style="color: #0000FF;">+</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">64</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">bytes_to_add</span><span style="color: #0000FF;">=</span><span style="color: #000000;">64</span> <span style="color: #008080;">then</span> <span style="color: #000000;">bytes_to_add</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">message</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">message</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">message</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">#80</span>
<span style="color: #000000;">message</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bytes_to_add</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">message</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">int_to_bytes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">l</span><span style="color: #0000FF;">*</span><span style="color: #000000;">8</span><span style="color: #0000FF;">)&{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">message</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #000000;">md5</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">message</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- Given a string, returns a 16-byte hash of it.</span>
<span style="color: #000000;">words</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">c_words</span> <span style="color: #000080;font-style:italic;">-- Initialize the H words</span>
<span style="color: #000000;">message</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">pad_message</span><span style="color: #0000FF;">(</span><span style="color: #000000;">message</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Add bytes to the message
-- Process each 64-byte block</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">block</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">message</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">by</span> <span style="color: #000000;">64</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">process_block</span><span style="color: #0000FF;">(</span><span style="color: #000000;">message</span><span style="color: #0000FF;">[</span><span style="color: #000000;">block</span><span style="color: #0000FF;">..</span><span style="color: #000000;">block</span><span style="color: #0000FF;">+</span><span style="color: #000000;">63</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- Convert hash into bytes</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">int_to_bytes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])&</span> <span style="color: #000080;font-style:italic;">-- Return the hash</span>
<span style="color: #7060A8;">int_to_bytes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">])&</span>
<span style="color: #7060A8;">int_to_bytes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">])&</span>
<span style="color: #7060A8;">int_to_bytes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">or</span> <span style="color: #7060A8;">include_file</span><span style="color: #0000FF;">()=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"0x%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X\n"</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">md5</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">md5</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"a"</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">md5</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"abc"</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">md5</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"message digest"</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">md5</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"abcdefghijklmnopqrstuvwxyz"</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">md5</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">md5</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"12345678901234567890123456789012345678901234567890123456789012345678901234567890"</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
0xd41d8cd98f00b204e9800998ecf8427e
0x0cc175b9c0f1b6a831c399e269772661
0x900150983cd24fb0d6963f7d28e17f72
0xf96b697d7cb7938d525a2f31aaf161d0
0xc3fcd3d76192e4007dfb496cca67e13b
0xd174ab98d277d9f5a5611c2c9f419d9f
0x57edf4a22be3c955ac49da2e2107b67a
</pre>
 
=={{header|PicoLisp}}==
Line 2,064 ⟶ 4,611:
care had to be taken with modulo 32-bit arithmetics, as PicoLisp supports only
numbers of unspecified size.
<langsyntaxhighlight PicoLisplang="picolisp">(scl 12)
(load "@lib/math.l") # For 'sin'
 
Line 2,158 ⟶ 4,705:
(do 4 # Convert to little endian hex string
(link (pad 2 (hex (& N 255))))
(setq N (>> 8 N)) ) ) ) ) ) )</langsyntaxhighlight>
Output:
<pre>: (md5 "")
Line 2,181 ⟶ 4,728:
Note that the following code focuses on brevity and elegance instead of performance, since Python isn't very good at number crunching anyway. If performance is important, the best solution is to use the built-in '''md5''' module, written in C.
 
<langsyntaxhighlight lang="python">import math
 
rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
Line 2,242 ⟶ 4,789:
for message in demo:
print(md5_to_hex(md5(message)),' <= "',message.decode('ascii'),'"', sep='')
</syntaxhighlight>
</lang>
 
Implementation notes:
Line 2,252 ⟶ 4,799:
 
=={{header|Racket}}==
For an implementation of md5 in Racket see: github.com/pltracket/racket/blob/master/racket/collects/file/md5.rkt
<langsyntaxhighlight lang="racket">
#lang racket
(require file/md5)
(md5 #"Rosetta Code")
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang="racket">
#"cca1bf66b09554e10f837838c3d3efb1"
</syntaxhighlight>
</lang>
 
=={{header|REXXRaku}}==
(formerly Perl 6)
<lang rexx>/*REXX program to test the MD5 procedure as per the test suite in the */
{{works with|rakudo|2024-02}}
/* IETF RFC (1321) ─── The MD5 Message─Digest Algorithm. April 1992. */
<syntaxhighlight lang="raku" line>proto md5($msg) returns Blob is export {*}
multi md5(Str $msg) { md5 $msg.encode }
multi md5(Blob $msg) {
my buf8 $buf .= new;
$buf.write-uint32: $buf.elems, $_, LittleEndian for
reduce -> Blob $blob, blob32 $X {
blob32.new: $blob Z+
reduce -> $b, $i {
blob32.new:
$b[3],
$b[1] +
-> uint32 \x, \n { (x +< n) +| (x +> (32-n)) }(
($b[0] + (BEGIN Array.new:
{ ($^x +& $^y) +| (+^$x +& $^z) },
{ ($^x +& $^z) +| ($^y +& +^$z) },
{ $^x +^ $^y +^ $^z },
{ $^y +^ ($^x +| +^$^z) }
)[$i div 16](|$b[1..3]) +
(BEGIN blob32.new: map &floor ∘ * * 2**32 ∘ &abs ∘ &sin ∘ * + 1, ^64)[$i] +
$X[(BEGIN Blob.new: 16 X[R%] flat ($++, 5*$++ + 1, 3*$++ + 5, 7*$++) Xxx 16)[$i]]
) mod 2**32,
(BEGIN flat < 7 12 17 22 5 9 14 20 4 11 16 23 6 10 15 21 >.rotor(4) Xxx 4)[$i]
),
$b[1],
$b[2]
}, $blob, |^64;
},
(BEGIN blob32.new: 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476),
|map { blob32.new: @$_ },
{
$^b.push(blob8.new(@$_).read-uint32(0)) for (@$msg, 0x80, 0x00 xx (-($msg.elems + 1 + 8) % 64))
.flat.rotor(4);
$b.write-uint64: $b.elems, 8*$msg.elems, LittleEndian;
$b;
}(buf32.new)
.rotor(16);
$buf;
}
 
CHECK {
/*─────────────────────────────────────Md5 test suite (from above doc). */
use Test;
msg.1=''
msg.2='a'
msg.3='abc'
msg.4='message digest'
msg.5='abcdefghijklmnopqrstuvwxyz'
msg.6='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
msg.7='12345678901234567890123456789012345678901234567890123456789012345678901234567890'
msg.0=7
do m=1 for msg.0
say ' in =' msg.m
say 'out =' MD5(msg.m)
say
end /*m*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────MD5 subroutine──────────────────────*/
MD5: procedure; parse arg !; numeric digits 20 /*insure enough digits.*/
parse value '67452301'x 'efcdab89'x '98badcfe'x '10325476'x with a b c d
#=length(!)
L=#*8 // 512
select
when L<448 then plus=448-L
when L>448 then plus=960-L
when L=448 then plus=512
end /*select*/
 
for 'd41d8cd98f00b204e9800998ecf8427e', '',
$=!||'80'x||copies('0'x,plus%8-1)reverse(right(d2c(8*#),4,'0'x))||'00000000'x
'0cc175b9c0f1b6a831c399e269772661', 'a',
'900150983cd24fb0d6963f7d28e17f72', 'abc',
'f96b697d7cb7938d525a2f31aaf161d0', 'message digest',
'c3fcd3d76192e4007dfb496cca67e13b', 'abcdefghijklmnopqrstuvwxyz',
'd174ab98d277d9f5a5611c2c9f419d9f', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
'57edf4a22be3c955ac49da2e2107b67a', '12345678901234567890123456789012345678901234567890123456789012345678901234567890'
-> $expected, $msg {
my $digest = md5($msg).list».fmt('%02x').join;
is($digest, $expected, "$digest is MD5 digest of '$msg'");
}
done-testing;
}</syntaxhighlight>
 
{{out}}
do j=0 to length($)%64-1 /*process message (lots of steps)*/
<pre>1..7
a_=a; b_=b; c_=c; d_=d
ok 1 - d41d8cd98f00b204e9800998ecf8427e is MD5 digest of ''
chunk=j*64
ok 2 - 0cc175b9c0f1b6a831c399e269772661 is MD5 digest of 'a'
do k=1 for 16 /*process the message in chunks. */
ok 3 - 900150983cd24fb0d6963f7d28e17f72 is MD5 digest of 'abc'
!.k=reverse(substr($,chunk+1+4*(k-1),4))
ok 4 - f96b697d7cb7938d525a2f31aaf161d0 is MD5 digest of 'message digest'
end /*k*/
ok 5 - c3fcd3d76192e4007dfb496cca67e13b is MD5 digest of 'abcdefghijklmnopqrstuvwxyz'
ok 6 - d174ab98d277d9f5a5611c2c9f419d9f is MD5 digest of 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
ok 7 - 57edf4a22be3c955ac49da2e2107b67a is MD5 digest of '12345678901234567890123456789012345678901234567890123456789012345678901234567890'</pre>
 
=={{header|REXX}}==
a=.part1(a,b,c,d, 0, 7,3614090360) /* 1*/
This REXX program uses the test suite that is from the IETF RFC (1321) contained in the
d=.part1(d,a,b,c, 1,12,3905402710) /* 2*/
&nbsp; ''MD5 Message─Digest Algorithm'', &nbsp;
c=.part1(c,d,a,b, 2,17, 606105819) /* 3*/
<br>April 1992.
b=.part1(b,c,d,a, 3,22,3250441966) /* 4*/
<syntaxhighlight lang="rexx">/*REXX program tests the MD5 procedure (below) as per a test suite from IETF RFC (1321).*/
a=.part1(a,b,c,d, 4, 7,4118548399) /* 5*/
@.1 = /*─────MD5 test suite [from above doc].*/
d=.part1(d,a,b,c, 5,12,1200080426) /* 6*/
@.2 = 'a'
c=.part1(c,d,a,b, 6,17,2821735955) /* 7*/
@.3 = 'abc'
b=.part1(b,c,d,a, 7,22,4249261313) /* 8*/
@.4 = 'message digest'
a=.part1(a,b,c,d, 8, 7,1770035416) /* 9*/
@.5 = 'abcdefghijklmnopqrstuvwxyz'
d=.part1(d,a,b,c, 9,12,2336552879) /*10*/
@.6 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
c=.part1(c,d,a,b,10,17,4294925233) /*11*/
@.7 = 12345678901234567890123456789012345678901234567890123456789012345678901234567890
b=.part1(b,c,d,a,11,22,2304563134) /*12*/
@.0 = 7 /* [↑] last value doesn't need quotes.*/
a=.part1(a,b,c,d,12, 7,1804603682) /*13*/
do m=1 for @.0; say /*process each of the seven messages. */
d=.part1(d,a,b,c,13,12,4254626195) /*14*/
say ' in =' @.m /*display the in message. */
c=.part1(c,d,a,b,14,17,2792965006) /*15*/
say 'out =' MD5(@.m) /* " " out " */
b=.part1(b,c,d,a,15,22,1236535329) /*16*/
end /*m*/
a=.part2(a,b,c,d, 1, 5,4129170786) /*17*/
exit /*stick a fork in it, we're all done. */
d=.part2(d,a,b,c, 6, 9,3225465664) /*18*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
c=.part2(c,d,a,b,11,14, 643717713) /*19*/
MD5: procedure; parse arg !; numeric digits 20 /*insure there's enough decimal digits.*/
b=.part2(b,c,d,a, 0,20,3921069994) /*20*/
a= '67452301'x; b= "efcdab89"x; c= '98badcfe'x; d= "10325476"x
a=.part2(a,b,c,d, 5, 5,3593408605) /*21*/
#= length(!) /*length in bytes of the input message.*/
d=.part2(d,a,b,c,10, 9, 38016083) /*22*/
L= #*8//512; if L<448 then plus= 448 - L /*is the length less than 448 ? */
c=.part2(c,d,a,b,15,14,3634488961) /*23*/
if L>448 then plus= 960 - L /* " " " greater " " */
b=.part2(b,c,d,a, 4,20,3889429448) /*24*/
if L=448 then plus= 512 /* " " " equal to " */
a=.part2(a,b,c,d, 9, 5, 568446438) /*25*/
/* [↓] a little of this, ··· */
d=.part2(d,a,b,c,14, 9,3275163606) /*26*/
$=! || "80"x || copies('0'x,plus%8-1)reverse(right(d2c(8*#), 4, '0'x)) || '00000000'x
c=.part2(c,d,a,b, 3,14,4107603335) /*27*/
/* [↑] ··· and a little of that.*/
b=.part2(b,c,d,a, 8,20,1163531501) /*28*/
do j=0 for length($) % 64 /*process the message (lots of steps).*/
a=.part2(a,b,c,d,13, 5,2850285829) /*29*/
a_= a; b_= b; c_= c; d_= d /*save the original values for later.*/
d=.part2(d,a,b,c, 2, 9,4243563512) /*30*/
chunk= j * 64 /*calculate the size of the chunks. */
c=.part2(c,d,a,b, 7,14,1735328473) /*31*/
do k=1 for 16 /*process the message in chunks. */
b=.part2(b,c,d,a,12,20,2368359562) /*32*/
!.k= reverse( substr($, chunk + 1 + 4*(k-1), 4) ) /*magic stuff.*/
a=.part3(a,b,c,d, 5, 4,4294588738) /*33*/
end /*k*/ /*────step────*/
d=.part3(d,a,b,c, 8,11,2272392833) /*34*/
a = .p1( a, b, c, d, 0, 7, 3614090360) /*■■■■ 1 ■■■■*/
c=.part3(c,d,a,b,11,16,1839030562) /*35*/
d = .p1( d, a, b, c, 1, 12, 3905402710) /*■■■■ 2 ■■■■*/
b=.part3(b,c,d,a,14,23,4259657740) /*36*/
c = .p1( c, d, a, b, 2, 17, 606105819) /*■■■■ 3 ■■■■*/
a=.part3(a,b,c,d, 1, 4,2763975236) /*37*/
b = .p1( b, c, d, a, 3, 22, 3250441966) /*■■■■ 4 ■■■■*/
d=.part3(d,a,b,c, 4,11,1272893353) /*38*/
a = .p1( a, b, c, d, 4, 7, 4118548399) /*■■■■ 5 ■■■■*/
c=.part3(c,d,a,b, 7,16,4139469664) /*39*/
d = .p1( d, a, b, c, 5, 12, 1200080426) /*■■■■ 6 ■■■■*/
b=.part3(b,c,d,a,10,23,3200236656) /*40*/
c = .p1( c, d, a, b, 6, 17, 2821735955) /*■■■■ 7 ■■■■*/
a=.part3(a,b,c,d,13, 4, 681279174) /*41*/
b = .p1( b, c, d, a, 7, 22, 4249261313) /*■■■■ 8 ■■■■*/
d=.part3(d,a,b,c, 0,11,3936430074) /*42*/
a = .p1( a, b, c, d, 8, 7, 1770035416) /*■■■■ 9 ■■■■*/
c=.part3(c,d,a,b, 3,16,3572445317) /*43*/
d = .p1( d, a, b, c, 9, 12, 2336552879) /*■■■■ 10 ■■■■*/
b=.part3(b,c,d,a, 6,23, 76029189) /*44*/
c = .p1( c, d, a, b, 10, 17, 4294925233) /*■■■■ 11 ■■■■*/
a=.part3(a,b,c,d, 9, 4,3654602809) /*45*/
b = .p1( b, c, d, a, 11, 22, 2304563134) /*■■■■ 12 ■■■■*/
d=.part3(d,a,b,c,12,11,3873151461) /*46*/
a = .p1( a, b, c, d, 12, 7, 1804603682) /*■■■■ 13 ■■■■*/
c=.part3(c,d,a,b,15,16, 530742520) /*47*/
d = .p1( d, a, b, c, 13, 12, 4254626195) /*■■■■ 14 ■■■■*/
b=.part3(b,c,d,a, 2,23,3299628645) /*48*/
c = .p1( c, d, a, b, 14, 17, 2792965006) /*■■■■ 15 ■■■■*/
a=.part4(a,b,c,d, 0, 6,4096336452) /*49*/
b = .p1( b, c, d, a, 15, 22, 1236535329) /*■■■■ 16 ■■■■*/
d=.part4(d,a,b,c, 7,10,1126891415) /*50*/
a = .p2( a, b, c, d, 1, 5, 4129170786) /*■■■■ 17 ■■■■*/
c=.part4(c,d,a,b,14,15,2878612391) /*51*/
d = .p2( d, a, b, c, 6, 9, 3225465664) /*■■■■ 18 ■■■■*/
b=.part4(b,c,d,a, 5,21,4237533241) /*52*/
c = .p2( c, d, a, b, 11, 14, 643717713) /*■■■■ 19 ■■■■*/
a=.part4(a,b,c,d,12, 6,1700485571) /*53*/
b = .p2( b, c, d, a, 0, 20, 3921069994) /*■■■■ 20 ■■■■*/
d=.part4(d,a,b,c, 3,10,2399980690) /*54*/
a = .p2( a, b, c, d, 5, 5, 3593408605) /*■■■■ 21 ■■■■*/
c=.part4(c,d,a,b,10,15,4293915773) /*55*/
d = .p2( d, a, b, c, 10, 9, 38016083) /*■■■■ 22 ■■■■*/
b=.part4(b,c,d,a, 1,21,2240044497) /*56*/
c = .p2( c, d, a, b, 15, 14, 3634488961) /*■■■■ 23 ■■■■*/
a=.part4(a,b,c,d, 8, 6,1873313359) /*57*/
b = .p2( b, c, d, a, 4, 20, 3889429448) /*■■■■ 24 ■■■■*/
d=.part4(d,a,b,c,15,10,4264355552) /*58*/
a = .p2( a, b, c, d, 9, 5, 568446438) /*■■■■ 25 ■■■■*/
c=.part4(c,d,a,b, 6,15,2734768916) /*59*/
d = .p2( d, a, b, c, 14, 9, 3275163606) /*■■■■ 26 ■■■■*/
b=.part4(b,c,d,a,13,21,1309151649) /*60*/
c = .p2( c, d, a, b, 3, 14, 4107603335) /*■■■■ 27 ■■■■*/
a=.part4(a,b,c,d, 4, 6,4149444226) /*61*/
b = .p2( b, c, d, a, 8, 20, 1163531501) /*■■■■ 28 ■■■■*/
d=.part4(d,a,b,c,11,10,3174756917) /*62*/
a = .p2( a, b, c, d, 13, 5, 2850285829) /*■■■■ 29 ■■■■*/
c=.part4(c,d,a,b, 2,15, 718787259) /*63*/
d = .p2( d, a, b, c, 2, 9, 4243563512) /*■■■■ 30 ■■■■*/
b=.part4(b,c,d,a, 9,21,3951481745) /*64*/
a c = .ap2(a_ c,a); d, b=.a(b_, b);, 7, c=.a(c_ 14,c 1735328473); d=.a(d_,d) /*■■■■ 31 ■■■■*/
b = .p2( b, c, d, a, 12, 20, 2368359562) /*■■■■ 32 ■■■■*/
end /*j*/
a = .p3( a, b, c, d, 5, 4, 4294588738) /*■■■■ 33 ■■■■*/
 
d = .p3( d, a, b, c, 8, 11, 2272392833) /*■■■■ 34 ■■■■*/
return c2x(reverse(a))c2x(reverse(b))c2x(reverse(c))c2x(reverse(d))
c = .p3( c, d, a, b, 11, 16, 1839030562) /*■■■■ 35 ■■■■*/
/*─────────────────────────────────────subroutines──────────────────────*/
b = .p3( b, c, d, a, 14, 23, 4259657740) /*■■■■ 36 ■■■■*/
.part1: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1
a = .p3( a, b, c, d, 1, 4, 2763975236) /*■■■■ 37 ■■■■*/
return .a(.lR(right(d2c(_+c2d(w)+c2d(.f(x,y,z))+c2d(!.n)),4,'0'x),m),x)
d = .p3( d, a, b, c, 4, 11, 1272893353) /*■■■■ 38 ■■■■*/
.part2: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1
c = .p3( c, d, a, b, 7, 16, 4139469664) /*■■■■ 39 ■■■■*/
return .a(.lR(right(d2c(_+c2d(w)+c2d(.g(x,y,z))+c2d(!.n)),4,'0'x),m),x)
b = .p3( b, c, d, a, 10, 23, 3200236656) /*■■■■ 40 ■■■■*/
.part3: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1
a = .p3( a, b, c, d, 13, 4, 681279174) /*■■■■ 41 ■■■■*/
return .a(.lR(right(d2c(_+c2d(w)+c2d(.h(x,y,z))+c2d(!.n)),4,'0'x),m),x)
d = .p3( d, a, b, c, 0, 11, 3936430074) /*■■■■ 42 ■■■■*/
.part4: procedure expose !.; parse arg w,x,y,z,n,m; n=n+1
c = .p3( c, d, a, b, 3, 16, 3572445317) /*■■■■ 43 ■■■■*/
return .a(.lR(right(d2c(c2d(w)+c2d(.i(x,y,z))+c2d(!.n)+arg(7)),4,'0'x),m),x)
b = .p3( b, c, d, a, 6, 23, 76029189) /*■■■■ 44 ■■■■*/
.h: procedure; parse arg x,y,z; return bitxor(bitxor(x,y),z)
a = .p3( a, b, c, d, 9, 4, 3654602809) /*■■■■ 45 ■■■■*/
.i: return bitxor(arg(2),bitor(arg(1),bitxor(arg(3),'ffffffff'x)))
d = .p3( d, a, b, c, 12, 11, 3873151461) /*■■■■ 46 ■■■■*/
.a: return right(d2c(c2d(arg(1))+c2d(arg(2))),4,'0'x)
c = .p3( c, d, a, b, 15, 16, 530742520) /*■■■■ 47 ■■■■*/
.f: procedure; parse arg x,y,z
b = .p3( b, c, d, a, 2, 23, 3299628645) /*■■■■ 48 ■■■■*/
return bitor(bitand(x,y),bitand(bitxor(x,'ffffffff'x),z))
a = .p4( a, b, c, d, 0, 6, 4096336452) /*■■■■ 49 ■■■■*/
.g: procedure; parse arg x,y,z
d = .p4( d, a, b, c, 7, 10, 1126891415) /*■■■■ 50 ■■■■*/
return bitor(bitand(x,z),bitand(y,bitxor(z,'ffffffff'x)))
c = .p4( c, d, a, b, 14, 15, 2878612391) /*■■■■ 51 ■■■■*/
.lR: procedure; parse arg _,#; if #==0 then return _ /*left rotate.*/
b = .p4( b, c, d, a, 5, 21, 4237533241) /*■■■■ 52 ■■■■*/
?=x2b(c2x(_)); return x2c(b2x(right(?||left(?,#),length(?))))</lang>
a = .p4( a, b, c, d, 12, 6, 1700485571) /*■■■■ 53 ■■■■*/
'''output'''
d = .p4( d, a, b, c, 3, 10, 2399980690) /*■■■■ 54 ■■■■*/
c = .p4( c, d, a, b, 10, 15, 4293915773) /*■■■■ 55 ■■■■*/
b = .p4( b, c, d, a, 1, 21, 2240044497) /*■■■■ 56 ■■■■*/
a = .p4( a, b, c, d, 8, 6, 1873313359) /*■■■■ 57 ■■■■*/
d = .p4( d, a, b, c, 15, 10, 4264355552) /*■■■■ 58 ■■■■*/
c = .p4( c, d, a, b, 6, 15, 2734768916) /*■■■■ 59 ■■■■*/
b = .p4( b, c, d, a, 13, 21, 1309151649) /*■■■■ 60 ■■■■*/
a = .p4( a, b, c, d, 4, 6, 4149444226) /*■■■■ 61 ■■■■*/
d = .p4( d, a, b, c, 11, 10, 3174756917) /*■■■■ 62 ■■■■*/
c = .p4( c, d, a, b, 2, 15, 718787259) /*■■■■ 63 ■■■■*/
b = .p4( b, c, d, a, 9, 21, 3951481745) /*■■■■ 64 ■■■■*/
a = .a(a_, a); b=.a(b_, b); c=.a(c_, c); d=.a(d_, d)
end /*j*/
return .rx(a).rx(b).rx(c).rx(d) /*same as: .rx(a) || .rx(b) || ··· */
/*──────────────────────────────────────────────────────────────────────────────────────*/
.a: return right( d2c( c2d( arg(1) ) + c2d( arg(2) ) ), 4, '0'x)
.h: return bitxor( bitxor( arg(1), arg(2) ), arg(3) )
.i: return bitxor( arg(2), bitor(arg(1), bitxor(arg(3), 'ffffffff'x) ) )
.f: return bitor( bitand(arg(1), arg(2)), bitand(bitxor(arg(1), 'ffffffff'x), arg(3) ) )
.g: return bitor( bitand(arg(1), arg(3)), bitand(arg(2), bitxor(arg(3), 'ffffffff'x) ) )
.rx: return c2x( reverse( arg(1) ) )
.Lr: procedure; parse arg _,#; if #==0 then return _ /*left bit rotate.*/
?=x2b(c2x(_)); return x2c( b2x( right(? || left(?, #), length(?) ) ) )
.p1: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n + 1
return .a(.Lr(right(d2c(_+c2d(w) + c2d(.f(x,y,z)) + c2d(!.n)),4,'0'x),m),x)
.p2: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n + 1
return .a(.Lr(right(d2c(_+c2d(w) + c2d(.g(x,y,z)) + c2d(!.n)),4,'0'x),m),x)
.p3: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n + 1
return .a(.Lr(right(d2c(_+c2d(w) + c2d(.h(x,y,z)) + c2d(!.n)),4,'0'x),m),x)
.p4: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n + 1
return .a(.Lr(right(d2c(c2d(w) + c2d(.i(x,y,z)) + c2d(!.n)+_),4,'0'x),m),x)</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
in =
Line 2,410 ⟶ 5,019:
in = 12345678901234567890123456789012345678901234567890123456789012345678901234567890
out = 57EDF4A22BE3C955AC49DA2E2107B67A
</pre>
 
=={{header|RPG}}==
Based on my Java implementation. Uses free-form RPG and a CTDATA section to hold lookup tables. Converts input from EBCDIC to ASCII before hashing.
 
<syntaxhighlight lang="rpg">**FREE
Ctl-opt MAIN(Main);
Ctl-opt DFTACTGRP(*NO) ACTGRP(*NEW);
 
dcl-pr QDCXLATE EXTPGM('QDCXLATE');
dataLen packed(5 : 0) CONST;
data char(32767) options(*VARSIZE);
conversionTable char(10) CONST;
end-pr;
 
dcl-c MASK32 CONST(4294967295);
dcl-s SHIFT_AMTS int(3) dim(16) CTDATA PERRCD(16);
dcl-s MD5_TABLE_T int(20) dim(64) CTDATA PERRCD(4);
 
dcl-proc Main;
dcl-s inputData char(45);
dcl-s inputDataLen int(10) INZ(0);
dcl-s outputHash char(16);
dcl-s outputHashHex char(32);
DSPLY 'Input: ' '' inputData;
inputData = %trim(inputData);
inputDataLen = %len(%trim(inputData));
DSPLY ('Input=' + inputData);
DSPLY ('InputLen=' + %char(inputDataLen));
// Convert from EBCDIC to ASCII
if inputDataLen > 0;
QDCXLATE(inputDataLen : inputData : 'QTCPASC');
endif;
CalculateMD5(inputData : inputDataLen : outputHash);
// Convert to hex
ConvertToHex(outputHash : 16 : outputHashHex);
DSPLY ('MD5: ' + outputHashHex);
return;
end-proc;
 
dcl-proc CalculateMD5;
dcl-pi *N;
message char(65535) options(*VARSIZE) CONST;
messageLen int(10) value;
outputHash char(16);
end-pi;
dcl-s numBlocks int(10);
dcl-s padding char(72);
dcl-s a int(20) INZ(1732584193);
dcl-s b int(20) INZ(4023233417);
dcl-s c int(20) INZ(2562383102);
dcl-s d int(20) INZ(271733878);
dcl-s buffer int(20) dim(16) INZ(0);
dcl-s i int(10);
dcl-s j int(10);
dcl-s k int(10);
dcl-s multiplier int(20);
dcl-s index int(10);
dcl-s originalA int(20);
dcl-s originalB int(20);
dcl-s originalC int(20);
dcl-s originalD int(20);
dcl-s div16 int(10);
dcl-s f int(20);
dcl-s tempInt int(20);
dcl-s bufferIndex int(10);
dcl-ds byteToInt QUALIFIED;
n int(5) INZ(0);
c char(1) OVERLAY(n : 2);
end-ds;
numBlocks = (messageLen + 8) / 64 + 1;
MD5_FillPadding(messageLen : numBlocks : padding);
for i = 0 to numBlocks - 1;
index = i * 64;
// Read message as little-endian 32-bit words
for j = 1 to 16;
multiplier = 1;
for k = 1 to 4;
index += 1;
if index <= messageLen;
byteToInt.c = %subst(message : index : 1);
else;
byteToInt.c = %subst(padding : index - messageLen : 1);
endif;
buffer(j) += multiplier * byteToInt.n;
multiplier *= 256;
endfor;
endfor;
originalA = a;
originalB = b;
originalC = c;
originalD = d;
for j = 0 to 63;
div16 = j / 16;
select;
when div16 = 0;
f = %bitor(%bitand(b : c) : %bitand(%bitnot(b) : d));
bufferIndex = j;
when div16 = 1;
f = %bitor(%bitand(b : d) : %bitand(c : %bitnot(d)));
bufferIndex = %bitand(j * 5 + 1 : 15);
when div16 = 2;
f = %bitxor(b : %bitxor(c : d));
bufferIndex = %bitand(j * 3 + 5 : 15);
when div16 = 3;
f = %bitxor(c : %bitor(b : Mask32Bit(%bitnot(d))));
bufferIndex = %bitand(j * 7 : 15);
endsl;
tempInt = Mask32Bit(b + RotateLeft32Bit(a + f + buffer(bufferIndex + 1) + MD5_TABLE_T(j + 1) :
SHIFT_AMTS(div16 * 4 + %bitand(j : 3) + 1)));
a = d;
d = c;
c = b;
b = tempInt;
endfor;
a = Mask32Bit(a + originalA);
b = Mask32Bit(b + originalB);
c = Mask32Bit(c + originalC);
d = Mask32Bit(d + originalD);
endfor;
for i = 0 to 3;
if i = 0;
tempInt = a;
elseif i = 1;
tempInt = b;
elseif i = 2;
tempInt = c;
else;
tempInt = d;
endif;
for j = 0 to 3;
byteToInt.n = %bitand(tempInt : 255);
%subst(outputHash : i * 4 + j + 1 : 1) = byteToInt.c;
tempInt /= 256;
endfor;
endfor;
return;
end-proc;
 
dcl-proc MD5_FillPadding;
dcl-pi *N;
messageLen int(10);
numBlocks int(10);
padding char(72);
end-pi;
dcl-s totalLen int(10);
dcl-s paddingSize int(10);
dcl-ds *N;
messageLenBits int(20);
mlb_bytes char(8) OVERLAY(messageLenBits);
end-ds;
dcl-s i int(10);
%subst(padding : 1 : 1) = X'80';
totalLen = numBlocks * 64;
paddingSize = totalLen - messageLen; // 9 to 72
messageLenBits = messageLen;
messageLenBits *= 8;
for i = 1 to 8;
%subst(padding : paddingSize - i + 1 : 1) = %subst(mlb_bytes : i : 1);
endfor;
for i = 2 to paddingSize - 8;
%subst(padding : i : 1) = X'00';
endfor;
return;
end-proc;
 
dcl-proc RotateLeft32Bit;
dcl-pi *N int(20);
n int(20) value;
amount int(3) value;
end-pi;
dcl-s i int(3);
n = Mask32Bit(n);
for i = 1 to amount;
n *= 2;
if n >= 4294967296;
n -= MASK32;
endif;
endfor;
return n;
end-proc;
 
dcl-proc Mask32Bit;
dcl-pi *N int(20);
n int(20) value;
end-pi;
return %bitand(n : MASK32);
end-proc;
 
dcl-proc ConvertToHex;
dcl-pi *N;
inputData char(32767) options(*VARSIZE) CONST;
inputDataLen int(10) value;
outputData char(65534) options(*VARSIZE);
end-pi;
dcl-c HEX_CHARS CONST('0123456789ABCDEF');
dcl-s i int(10);
dcl-s outputOffset int(10) INZ(1);
dcl-ds dataStruct QUALIFIED;
numField int(5) INZ(0);
// IBM i is big-endian
charField char(1) OVERLAY(numField : 2);
end-ds;
for i = 1 to inputDataLen;
dataStruct.charField = %BitAnd(%subst(inputData : i : 1) : X'F0');
dataStruct.numField /= 16;
%subst(outputData : outputOffset : 1) = %subst(HEX_CHARS : dataStruct.numField + 1 : 1);
outputOffset += 1;
dataStruct.charField = %BitAnd(%subst(inputData : i : 1) : X'0F');
%subst(outputData : outputOffset : 1) = %subst(HEX_CHARS : dataStruct.numField + 1 : 1);
outputOffset += 1;
endfor;
return;
end-proc;
 
**CTDATA SHIFT_AMTS
7 12 17 22 5 9 14 20 4 11 16 23 6 10 15 21
**CTDATA MD5_TABLE_T
3614090360 3905402710 606105819 3250441966
4118548399 1200080426 2821735955 4249261313
1770035416 2336552879 4294925233 2304563134
1804603682 4254626195 2792965006 1236535329
4129170786 3225465664 643717713 3921069994
3593408605 38016083 3634488961 3889429448
568446438 3275163606 4107603335 1163531501
2850285829 4243563512 1735328473 2368359562
4294588738 2272392833 1839030562 4259657740
2763975236 1272893353 4139469664 3200236656
681279174 3936430074 3572445317 76029189
3654602809 3873151461 530742520 3299628645
4096336452 1126891415 2878612391 4237533241
1700485571 2399980690 4293915773 2240044497
1873313359 4264355552 2734768916 1309151649
4149444226 3174756917 718787259 3951481745</syntaxhighlight>
 
Sample output:
<pre> DSPLY Input:
abcdefghijklmnopqrstuvwxyz
DSPLY Input=abcdefghijklmnopqrstuvwxyz
DSPLY InputLen=26
DSPLY MD5: C3FCD3D76192E4007DFB496CCA67E13B</pre>
 
=={{header|Rust}}==
 
A translation of RFC (1321), to highlight the algorithm itself in bare form. Notable Rust features are the strict limits on casting, explicit description of bit-widths and wrap-around operations, and macros for the Rounds. This made it easy to translate and debug, although a bit 'wordy' in sections, and requiring special code to transliterate between strings and integers.
 
Reasonable speed was desired; Profiling revealed the "copy block to X" loop as hot. This loops casts arrays of 8 bit integers into 32 bit integers, which Rust does very slowly in 'safe' code, so an unsafe transmute, and, on big-endian machines a byteswap, was used. Runtime is 120-150% slower than standard linux /usr/bin/md5sum.
 
As with others implementations, this will not allow bit-lengths non-divisible by 8; this ability can be added in about 8 lines of code but no examples appear to be available for verification of correctness, and so it was elided.
 
<syntaxhighlight lang="rust">
#![allow(non_snake_case)] // RFC 1321 uses many capitalized variables
use std::mem;
 
fn md5(mut msg: Vec<u8>) -> (u32, u32, u32, u32) {
let bitcount = msg.len().saturating_mul(8) as u64;
 
// Step 1: Append Padding Bits
msg.push(0b10000000);
while (msg.len() * 8) % 512 != 448 {
msg.push(0u8);
}
 
// Step 2. Append Length (64 bit integer)
msg.extend(&[
bitcount as u8,
(bitcount >> 8) as u8,
(bitcount >> 16) as u8,
(bitcount >> 24) as u8,
(bitcount >> 32) as u8,
(bitcount >> 40) as u8,
(bitcount >> 48) as u8,
(bitcount >> 56) as u8,
]);
 
// Step 3. Initialize MD Buffer
/*A four-word buffer (A,B,C,D) is used to compute the message digest.
Here each of A, B, C, D is a 32-bit register.*/
let mut A = 0x67452301u32;
let mut B = 0xefcdab89u32;
let mut C = 0x98badcfeu32;
let mut D = 0x10325476u32;
 
// Step 4. Process Message in 16-Word Blocks
/* We first define four auxiliary functions */
let F = |X: u32, Y: u32, Z: u32| -> u32 { X & Y | !X & Z };
let G = |X: u32, Y: u32, Z: u32| -> u32 { X & Z | Y & !Z };
let H = |X: u32, Y: u32, Z: u32| -> u32 { X ^ Y ^ Z };
let I = |X: u32, Y: u32, Z: u32| -> u32 { Y ^ (X | !Z) };
 
/* This step uses a 64-element table T[1 ... 64] constructed from the sine function. */
let T = [
0x00000000, // enable use as a 1-indexed table
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613,
0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193,
0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d,
0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122,
0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa,
0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244,
0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb,
0xeb86d391,
];
 
/* Process each 16-word block. (since 1 word is 4 bytes, then 16 words is 64 bytes) */
for mut block in msg.chunks_exact_mut(64) {
/* Copy block into X. */
#![allow(unused_mut)]
let mut X = unsafe { mem::transmute::<&mut [u8], &mut [u32]>(&mut block) };
#[cfg(target_endian = "big")]
for j in 0..16 {
X[j] = X[j].swap_bytes();
}
 
/* Save Registers A,B,C,D */
let AA = A;
let BB = B;
let CC = C;
let DD = D;
 
/* Round 1. Let [abcd k s i] denote the operation
a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
macro_rules! op1 {
($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {
$a = $b.wrapping_add(
($a.wrapping_add(F($b, $c, $d))
.wrapping_add(X[$k])
.wrapping_add(T[$i]))
.rotate_left($s),
)
};
}
 
/* Do the following 16 operations. */
op1!(A, B, C, D, 0, 7, 1);
op1!(D, A, B, C, 1, 12, 2);
op1!(C, D, A, B, 2, 17, 3);
op1!(B, C, D, A, 3, 22, 4);
 
op1!(A, B, C, D, 4, 7, 5);
op1!(D, A, B, C, 5, 12, 6);
op1!(C, D, A, B, 6, 17, 7);
op1!(B, C, D, A, 7, 22, 8);
 
op1!(A, B, C, D, 8, 7, 9);
op1!(D, A, B, C, 9, 12, 10);
op1!(C, D, A, B, 10, 17, 11);
op1!(B, C, D, A, 11, 22, 12);
 
op1!(A, B, C, D, 12, 7, 13);
op1!(D, A, B, C, 13, 12, 14);
op1!(C, D, A, B, 14, 17, 15);
op1!(B, C, D, A, 15, 22, 16);
 
/* Round 2. Let [abcd k s i] denote the operation
a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
macro_rules! op2 {
($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {
$a = $b.wrapping_add(
($a.wrapping_add(G($b, $c, $d))
.wrapping_add(X[$k])
.wrapping_add(T[$i]))
.rotate_left($s),
)
};
}
 
/* Do the following 16 operations. */
op2!(A, B, C, D, 1, 5, 17);
op2!(D, A, B, C, 6, 9, 18);
op2!(C, D, A, B, 11, 14, 19);
op2!(B, C, D, A, 0, 20, 20);
 
op2!(A, B, C, D, 5, 5, 21);
op2!(D, A, B, C, 10, 9, 22);
op2!(C, D, A, B, 15, 14, 23);
op2!(B, C, D, A, 4, 20, 24);
 
op2!(A, B, C, D, 9, 5, 25);
op2!(D, A, B, C, 14, 9, 26);
op2!(C, D, A, B, 3, 14, 27);
op2!(B, C, D, A, 8, 20, 28);
 
op2!(A, B, C, D, 13, 5, 29);
op2!(D, A, B, C, 2, 9, 30);
op2!(C, D, A, B, 7, 14, 31);
op2!(B, C, D, A, 12, 20, 32);
 
/* Round 3. Let [abcd k s t] denote the operation
a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
macro_rules! op3 {
($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {
$a = $b.wrapping_add(
($a.wrapping_add(H($b, $c, $d))
.wrapping_add(X[$k])
.wrapping_add(T[$i]))
.rotate_left($s),
)
};
}
 
/* Do the following 16 operations. */
op3!(A, B, C, D, 5, 4, 33);
op3!(D, A, B, C, 8, 11, 34);
op3!(C, D, A, B, 11, 16, 35);
op3!(B, C, D, A, 14, 23, 36);
 
op3!(A, B, C, D, 1, 4, 37);
op3!(D, A, B, C, 4, 11, 38);
op3!(C, D, A, B, 7, 16, 39);
op3!(B, C, D, A, 10, 23, 40);
 
op3!(A, B, C, D, 13, 4, 41);
op3!(D, A, B, C, 0, 11, 42);
op3!(C, D, A, B, 3, 16, 43);
op3!(B, C, D, A, 6, 23, 44);
 
op3!(A, B, C, D, 9, 4, 45);
op3!(D, A, B, C, 12, 11, 46);
op3!(C, D, A, B, 15, 16, 47);
op3!(B, C, D, A, 2, 23, 48);
 
/* Round 4. Let [abcd k s t] denote the operation
a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
macro_rules! op4 {
($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {
$a = $b.wrapping_add(
($a.wrapping_add(I($b, $c, $d))
.wrapping_add(X[$k])
.wrapping_add(T[$i]))
.rotate_left($s),
)
};
}
 
/* Do the following 16 operations. */
op4!(A, B, C, D, 0, 6, 49);
op4!(D, A, B, C, 7, 10, 50);
op4!(C, D, A, B, 14, 15, 51);
op4!(B, C, D, A, 5, 21, 52);
 
op4!(A, B, C, D, 12, 6, 53);
op4!(D, A, B, C, 3, 10, 54);
op4!(C, D, A, B, 10, 15, 55);
op4!(B, C, D, A, 1, 21, 56);
 
op4!(A, B, C, D, 8, 6, 57);
op4!(D, A, B, C, 15, 10, 58);
op4!(C, D, A, B, 6, 15, 59);
op4!(B, C, D, A, 13, 21, 60);
 
op4!(A, B, C, D, 4, 6, 61);
op4!(D, A, B, C, 11, 10, 62);
op4!(C, D, A, B, 2, 15, 63);
op4!(B, C, D, A, 9, 21, 64);
 
/* . . . increment each of the four registers by the value
it had before this block was started.) */
 
A = A.wrapping_add(AA);
B = B.wrapping_add(BB);
C = C.wrapping_add(CC);
D = D.wrapping_add(DD);
}
(
A.swap_bytes(),
B.swap_bytes(),
C.swap_bytes(),
D.swap_bytes(),
)
}
 
fn md5_utf8(smsg: &str) -> String {
let mut msg = vec![0u8; 0];
msg.extend(smsg.as_bytes());
let (A, B, C, D) = md5(msg);
format!("{:08x}{:08x}{:08x}{:08x}", A, B, C, D)
}
 
fn main() {
assert!(md5_utf8("") == "d41d8cd98f00b204e9800998ecf8427e");
assert!(md5_utf8("a") == "0cc175b9c0f1b6a831c399e269772661");
assert!(md5_utf8("abc") == "900150983cd24fb0d6963f7d28e17f72");
assert!(md5_utf8("message digest") == "f96b697d7cb7938d525a2f31aaf161d0");
assert!(md5_utf8("abcdefghijklmnopqrstuvwxyz") == "c3fcd3d76192e4007dfb496cca67e13b");
assert!(md5_utf8("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") == "d174ab98d277d9f5a5611c2c9f419d9f");
assert!(md5_utf8("12345678901234567890123456789012345678901234567890123456789012345678901234567890") == "57edf4a22be3c955ac49da2e2107b67a");
}
</syntaxhighlight>
 
=={{header|Scala}}==
 
{{trans|Java}}
 
 
Based on RFC-1321.
 
 
<syntaxhighlight lang="Scala">
import java.lang.Math
 
object MD5 {
private val INIT_A = 0x67452301
private val INIT_B = 0xEFCDAB89
private val INIT_C = 0x98BADCFE
private val INIT_D = 0x10325476
 
private val SHIFT_AMTS = Array(
7, 12, 17, 22,
5, 9, 14, 20,
4, 11, 16, 23,
6, 10, 15, 21
)
 
private val TABLE_T = Array.tabulate(64)(i => (Math.abs(Math.sin(i + 1)) * (1L << 32)).toLong.toInt)
 
def computeMD5(message: Array[Byte]): Array[Byte] = {
val messageLenBytes = message.length
val numBlocks = ((messageLenBytes + 8) >>> 6) + 1
val totalLen = numBlocks << 6
val paddingBytes = Array.fill[Byte](totalLen - messageLenBytes)(0)
paddingBytes(0) = 0x80.toByte
 
var messageLenBits = messageLenBytes.toLong << 3
for (i <- 0 until 8) {
paddingBytes(paddingBytes.length - 8 + i) = messageLenBits.toByte
messageLenBits >>>= 8
}
 
var a = INIT_A
var b = INIT_B
var c = INIT_C
var d = INIT_D
val buffer = new Array[Int](16)
 
for (i <- 0 until numBlocks) {
var index = i << 6
for (j <- 0 until 64) {
buffer(j >>> 2) = (((if (index < messageLenBytes) message(index) else paddingBytes(index - messageLenBytes)) << 24) | (buffer(j >>> 2) >>> 8)).toInt
index += 1
}
val originalA = a
val originalB = b
val originalC = c
val originalD = d
 
for (j <- 0 until 64) {
val div16 = j >>> 4
val bufferIndex = j match {
case j if j < 16 => j
case j if j < 32 => (j * 5 + 1) & 0x0F
case j if j < 48 => (j * 3 + 5) & 0x0F
case j => (j * 7) & 0x0F
}
 
val f = div16 match {
case 0 => (b & c) | (~b & d)
case 1 => (b & d) | (c & ~d)
case 2 => b ^ c ^ d
case 3 => c ^ (b | ~d)
}
 
val temp = b + Integer.rotateLeft(a + f + buffer(bufferIndex) + TABLE_T(j), SHIFT_AMTS((div16 << 2) | (j & 3)))
a = d
d = c
c = b
b = temp
}
 
a += originalA
b += originalB
c += originalC
d += originalD
}
 
val md5 = new Array[Byte](16)
var count = 0
for (i <- 0 until 4) {
var n = i match {
case 0 => a
case 1 => b
case 2 => c
case 3 => d
}
for (j <- 0 until 4) {
md5(count) = n.toByte
n >>>= 8
count += 1
}
}
md5
}
 
def toHexString(b: Array[Byte]): String = b.map(byte => f"$byte%02X").mkString
 
def main(args: Array[String]): Unit = {
val testStrings = Array("", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "12345678901234567890123456789012345678901234567890123456789012345678901234567890")
testStrings.foreach { s =>
println(s"0x${toHexString(computeMD5(s.getBytes))} <== \"$s\"")
}
}
}
</syntaxhighlight>
{{out}}
<pre>
0xD41D8CD98F00B204E9800998ECF8427E <== ""
0x0CC175B9C0F1B6A831C399E269772661 <== "a"
0x900150983CD24FB0D6963F7D28E17F72 <== "abc"
0xF96B697D7CB7938D525A2F31AAF161D0 <== "message digest"
0xC3FCD3D76192E4007DFB496CCA67E13B <== "abcdefghijklmnopqrstuvwxyz"
0xD174AB98D277D9F5A5611C2C9F419D9F <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57EDF4A22BE3C955AC49DA2E2107B67A <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
 
</pre>
 
Line 2,415 ⟶ 5,652:
The example below contains the implementation of the function [http://seed7.sourceforge.net/libraries/msgdigest.htm#md5%28in_var_string%29 md5] from the library [http://seed7.sourceforge.net/libraries/msgdigest.htm msgdigest.s7i].
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bytedata.s7i";
include "bin32.s7i";
Line 2,445 ⟶ 5,682:
const array integer: k is createMd5Table;
var integer: length is 0;
var integer: chunkIndexwordIndex is 01;
var integer: index is 0;
var array bin32: m is 16 times bin32.value;
Line 2,466 ⟶ 5,703:
message &:= "\0;" mult 63 - (length + 8) mod 64;
# Append length of message (before pre-processing), in bits, as 64-bit little-endian integer.
message &:= int64AsEightBytesLebytes(8 * length, UNSIGNED, LE, 8);
 
# Process the message in successive 512-bit chunks:
forwhile chunkIndexwordIndex range 1 to<= length(message) step 64 do
# Break chunk into sixteen 32-bit little-endian words.
for index range 1 to 16 do
m[index] := bin32(bytes2Int(message[chunkIndexwordIndex + 4 * pred(index) lenfixLen 4], UNSIGNED, LE));
wordIndex +:= 4;
end for;
 
Line 2,486 ⟶ 5,724:
elsif index <= 32 then
f := c >< (d & (b >< c));
g := succ((5 * index - 4) mod 16 + 1);
elsif index <= 48 then
f := b >< c >< d;
g := succ((3 * index + 2) mod 16 + 1);
else
f := c >< (b | (bin32(16#ffffffff) >< d));
g := succ((7 * pred(index)) mod 16 + 1);
end if;
 
Line 2,509 ⟶ 5,747:
c0 +:= ord(c);
d0 +:= ord(d);
end forwhile;
 
# Produce the final hash value:
digest := int32AsFourBytesLebytes(a0 mod 16#100000000, UNSIGNED, LE, 4) &
int32AsFourBytesLebytes(b0 mod 16#100000000, UNSIGNED, LE, 4) &
int32AsFourBytesLebytes(c0 mod 16#100000000, UNSIGNED, LE, 4) &
int32AsFourBytesLebytes(d0 mod 16#100000000, UNSIGNED, LE, 4);
end func;
 
Line 2,534 ⟶ 5,772:
writeln("There is an error in the md5 function");
end if;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/msgdigest.htm#md5]
Line 2,541 ⟶ 5,779:
<pre>
md5 is computed correct
</pre>
 
=={{header|Sidef}}==
{{trans|Raku}}
<syntaxhighlight lang="ruby">class MD5(String msg) {
 
method init {
msg = msg.bytes
}
 
const FGHI = [
{|a,b,c| (a & b) | (~a & c) },
{|a,b,c| (a & c) | (b & ~c) },
{|a,b,c| (a ^ b ^ c) },
{|a,b,c| (b ^ (a | ~c)) },
]
 
const S = [
[7, 12, 17, 22] * 4,
[5, 9, 14, 20] * 4,
[4, 11, 16, 23] * 4,
[6, 10, 15, 21] * 4,
].flat
 
const T = 64.of {|i| floor(abs(sin(i+1)) * 1<<32) }
 
const K = [
^16 -> map {|n| n },
^16 -> map {|n| (5*n + 1) % 16 },
^16 -> map {|n| (3*n + 5) % 16 },
^16 -> map {|n| (7*n ) % 16 },
].flat
 
func radix(Number b, Array a) {
^a -> sum {|i| b**i * a[i] }
}
 
func little_endian(Number w, Number n, Array v) {
var step1 = (^n »*» w)
var step2 = (v ~X>> step1)
step2 »%» (1 << w)
}
 
func block(Number a, Number b) { (a + b) & 0xffffffff }
func srble(Number a, Number n) { (a << n) & 0xffffffff | (a >> (32-n)) }
 
func md5_pad(msg) {
var bits = 8*msg.len
var padded = [msg..., 128, [0] * (-(floor(bits / 8) + 1 + 8) % 64)].flat
 
gather {
padded.each_slice(4, {|*a|
take(radix(256, a))
})
take(little_endian(32, 2, [bits]))
}.flat
}
 
func md5_block(Array H, Array X) {
var (A, B, C, D) = H...
 
for i in ^64 {
(A, B, C, D) = (D,
block(B, srble(
block(
block(
block(A, FGHI[floor(i / 16)](B, C, D)), T[i]
), X[K[i]]
), S[i])
), B, C)
}
 
for k,v in ([A, B, C, D].kv) {
H[k] = block(H[k], v)
}
 
return H
}
 
method md5_hex {
self.md5.map {|n| '%02x' % n }.join
}
 
method md5 {
var M = md5_pad(msg)
var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
 
for i in (range(0, M.end, 16)) {
md5_block(H, M.slice(i).first(16))
}
 
little_endian(8, 4, H)
}
}
 
var tests = [
['d41d8cd98f00b204e9800998ecf8427e', ''],
['0cc175b9c0f1b6a831c399e269772661', 'a'],
['900150983cd24fb0d6963f7d28e17f72', 'abc'],
['f96b697d7cb7938d525a2f31aaf161d0', 'message digest'],
['c3fcd3d76192e4007dfb496cca67e13b', 'abcdefghijklmnopqrstuvwxyz'],
['d174ab98d277d9f5a5611c2c9f419d9f', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'],
['57edf4a22be3c955ac49da2e2107b67a', '12345678901234567890123456789012345678901234567890123456789012345678901234567890'],
]
 
for md5,msg in tests {
var hash = MD5(msg).md5_hex
say "#{hash} : #{msg}"
 
if (hash != md5) {
say "\tHowever, that is incorrect (expected: #{md5})"
}
}</syntaxhighlight>
{{out}}
<pre>
d41d8cd98f00b204e9800998ecf8427e :
0cc175b9c0f1b6a831c399e269772661 : a
900150983cd24fb0d6963f7d28e17f72 : abc
f96b697d7cb7938d525a2f31aaf161d0 : message digest
c3fcd3d76192e4007dfb496cca67e13b : abcdefghijklmnopqrstuvwxyz
d174ab98d277d9f5a5611c2c9f419d9f : ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
57edf4a22be3c955ac49da2e2107b67a : 12345678901234567890123456789012345678901234567890123456789012345678901234567890
</pre>
 
Line 2,549 ⟶ 5,909:
Original source: [//github.com/krzyzanowskim/CryptoSwift CryptoSwift]
 
<langsyntaxhighlight lang="swift">
import Foundation
public class MD5 {
Line 2,676 ⟶ 6,036:
}
}
</syntaxhighlight>
</lang>
 
From-scratch implementation based on the solutions on this page without needing any external libraries:
<langsyntaxhighlight lang="swift">import Foundation
 
let shift : [UInt32] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21]
Line 2,761 ⟶ 6,121:
println(toHexString(md5(Array(string.utf8))))
println()
}</lang swiftsyntaxhighlight>
{{out}}
<pre>
Line 2,788 ⟶ 6,148:
=={{header|Tcl}}==
<small>This code is extracted from the <code>md5</code> package in {{libheader|tcllib}}, and is originally due to Don Libes's transcription of the code in the MD5 specification. ''It should not be deployed in production normally; the <code>md5</code> package should be used in preference as it is usually built to be faster.</small>
<langsyntaxhighlight lang="tcl"># We just define the body of md5::md5 here; later we regsub to inline a few
# function calls for speed
variable ::md5::md5body {
Line 3,032 ⟶ 6,392:
format %0.2x%0.2x%0.2x%0.2x [byte0 $i] [byte1 $i] [byte2 $i] [byte3 $i]
}
}</langsyntaxhighlight>
Demonstration code:
<langsyntaxhighlight lang="tcl">foreach {hash <- string} {
0xd41d8cd98f00b204e9800998ecf8427e ==> ""
0x0cc175b9c0f1b6a831c399e269772661 ==> "a"
Line 3,044 ⟶ 6,404:
} {
puts "“$string” -> [md5::md5 $string] (officially: $hash)"
}</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
This is a translation of the C code [https://github.com/pod32g/MD5/blob/master/md5.c here]. In the interests of brevity, the original comments have been omitted.
<syntaxhighlight lang="wren">import "./fmt" for Fmt
 
var k = [
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee ,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501 ,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be ,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 ,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa ,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8 ,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed ,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a ,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c ,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70 ,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05 ,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665 ,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039 ,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1 ,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1 ,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
]
 
var r = [
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
]
 
var leftRotate = Fn.new { |x, c| (x << c) | (x >> (32 - c)) }
 
var toBytes = Fn.new { |val|
var bytes = List.filled(4, 0)
bytes[0] = val & 255
bytes[1] = (val >> 8) & 255
bytes[2] = (val >> 16) & 255
bytes[3] = (val >> 24) & 255
return bytes
}
 
var toInt = Fn.new { |bytes| bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24 }
 
var md5 = Fn.new { |initMsg|
var h0 = 0x67452301
var h1 = 0xefcdab89
var h2 = 0x98badcfe
var h3 = 0x10325476
var initBytes = initMsg.bytes
var initLen = initBytes.count
var newLen = initLen + 1
while (newLen % 64 != 56) newLen = newLen + 1
var msg = List.filled(newLen + 8, 0)
for (i in 0...initLen) msg[i] = initBytes[i]
msg[initLen] = 0x80 // remaining bytes already 0
var lenBits = toBytes.call(initLen * 8)
for (i in newLen...newLen+4) msg[i] = lenBits[i-newLen]
var extraBits = toBytes.call(initLen >> 29)
for (i in newLen+4...newLen+8) msg[i] = extraBits[i-newLen-4]
var offset = 0
var w = List.filled(16, 0)
while (offset < newLen) {
for (i in 0...16) w[i] = toInt.call(msg[offset+i*4...offset + i*4 + 4])
var a = h0
var b = h1
var c = h2
var d = h3
var f
var g
for (i in 0...64) {
if (i < 16) {
f = (b & c) | ((~b) & d)
g = i
} else if (i < 32) {
f = (d & b) | ((~d) & c)
g = (5*i + 1) % 16
} else if (i < 48) {
f = b ^ c ^ d
g = (3*i + 5) % 16
} else {
f = c ^ (b | (~d))
g = (7*i) % 16
}
var temp = d
d = c
c = b
b = b + leftRotate.call((a + f + k[i] + w[g]), r[i])
a = temp
}
h0 = h0 + a
h1 = h1 + b
h2 = h2 + c
h3 = h3 + d
offset = offset + 64
}
var digest = List.filled(16, 0)
var dBytes = toBytes.call(h0)
for (i in 0...4) digest[i] = dBytes[i]
dBytes = toBytes.call(h1)
for (i in 0...4) digest[i+4] = dBytes[i]
dBytes = toBytes.call(h2)
for (i in 0...4) digest[i+8] = dBytes[i]
dBytes = toBytes.call(h3)
for (i in 0...4) digest[i+12] = dBytes[i]
return digest
}
 
var strings = [
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890"
]
 
for (s in strings) {
var digest = md5.call(s)
Fmt.print("0x$s <== '$0s'", Fmt.v("xz", 2, digest, 0, "", ""), s)
}</syntaxhighlight>
 
{{out}}
<pre>
0xd41d8cd98f00b204e9800998ecf8427e <== ''
0x0cc175b9c0f1b6a831c399e269772661 <== 'a'
0x900150983cd24fb0d6963f7d28e17f72 <== 'abc'
0xf96b697d7cb7938d525a2f31aaf161d0 <== 'message digest'
0xc3fcd3d76192e4007dfb496cca67e13b <== 'abcdefghijklmnopqrstuvwxyz'
0xd174ab98d277d9f5a5611c2c9f419d9f <== 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
0x57edf4a22be3c955ac49da2e2107b67a <== '12345678901234567890123456789012345678901234567890123456789012345678901234567890'
</pre>
 
=={{header|x86 Assembly}}==
Line 3,051 ⟶ 6,545:
Uses DOS interrupts for display.
 
<langsyntaxhighlight lang="asm">section .text
org 0x100
mov di, md5_for_display
Line 3,317 ⟶ 6,811:
test_input_6_len equ $ - test_input_6
test_input_7 db '12345678901234567890123456789012345678901234567890123456789012345678901234567890'
test_input_7_len equ $ - test_input_7</langsyntaxhighlight>
 
'''Output:'''
1,934

edits