This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

7
Task/MD5/0DESCRIPTION Normal file
View file

@ -0,0 +1,7 @@
Encode a string using an MD5 algorithm. The algorithm can be found on [[wp:Md5#Algorithm|wikipedia]].
Optionally, validate your implementation by running all of the test values in [http://tools.ietf.org/html/rfc1321 IETF RFC (1321) for MD5]. Additional the RFC provides more precise information on the algorithm than the Wikipedia article.
{{alertbox|lightgray|'''Warning:''' MD5 has [http://tools.ietf.org/html/rfc6151 known weaknesses], including '''collisions''' and [http://www.win.tue.nl/hashclash/rogue-ca/ forged signatures]. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}}
If the solution on this page is a library solution, see [[MD5/Implementation]] for an implementation from scratch.

2
Task/MD5/1META.yaml Normal file
View file

@ -0,0 +1,2 @@
---
note: Checksums

7
Task/MD5/Ada/md5.ada Normal file
View file

@ -0,0 +1,7 @@
with Ada.Text_IO; use Ada.Text_IO;
with GNAT.MD5;
procedure MD5_Digest is
begin
Put(GNAT.MD5.Digest("Foo bar baz"));
end MD5_Digest;

View file

@ -0,0 +1,12 @@
data := "abc"
MsgBox % MD5(data,StrLen(data)) ; 900150983cd24fb0d6963f7d28e17f72
MD5( ByRef V, L=0 ) {
VarSetCapacity( MD5_CTX,104,0 ), DllCall( "advapi32\MD5Init", Str,MD5_CTX )
DllCall( "advapi32\MD5Update", Str,MD5_CTX, Str,V, UInt,L ? L : VarSetCapacity(V) )
DllCall( "advapi32\MD5Final", Str,MD5_CTX )
Loop % StrLen( Hex:="123456789ABCDEF0" )
N := NumGet( MD5_CTX,87+A_Index,"Char"), MD5 .= SubStr(Hex,N>>4,1) . SubStr(Hex,N&15,1)
Return MD5
}
}

View file

@ -0,0 +1,75 @@
; GLOBAL CONSTANTS r[64], k[64]
r = 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
StringSplit r, r, `,
r0 := 7
Loop 64
i := A_Index-1, k%i% := floor(abs(sin(A_Index)) * 2**32)
; TEST CASES
MsgBox % MD5(x:="", 0) ; d41d8cd98f00b204e9800998ecf8427e
MsgBox % MD5(x:="a", StrLen(x)) ; 0cc175b9c0f1b6a831c399e269772661
MsgBox % MD5(x:="abc", StrLen(x)) ; 900150983cd24fb0d6963f7d28e17f72
MsgBox % MD5(x:="message digest", StrLen(x)) ; f96b697d7cb7938d525a2f31aaf161d0
MsgBox % MD5(x:="abcdefghijklmnopqrstuvwxyz", StrLen(x))
; c3fcd3d76192e4007dfb496cca67e13b
MsgBox % MD5(x:="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", StrLen(x))
; d174ab98d277d9f5a5611c2c9f419d9f
MsgBox % MD5(x:="12345678901234567890123456789012345678901234567890123456789012345678901234567890", StrLen(x))
; 57edf4a22be3c955ac49da2e2107b67a
MsgBox % MD5(x:="The quick brown fox jumps over the lazy dog", StrLen(x))
; 9e107d9d372bb6826bd81d3542a419d6
MsgBox % MD5(x:="The quick brown fox jumps over the lazy cog", StrLen(x))
; 1055d3e698d289f2af8663725127bd4b
MD5(ByRef Buf, L) { ; Binary buffer, Length in bytes
Static P, Q, N, i, a,b,c,d, t, h0,h1,h2,h3, y = 0xFFFFFFFF
h0 := 0x67452301, h1 := 0xEFCDAB89, h2 := 0x98BADCFE, h3 := 0x10325476
N := ceil((L+9)/64)*64 ; padded length (100..separator, 8B length)
VarSetCapacity(Q,N,0) ; room for padded data
P := &Q ; pointer
DllCall("RtlMoveMemory", UInt,P, UInt,&Buf, UInt,L) ; copy data
DllCall("RtlFillMemory", UInt,P+L, UInt,1, UInt,0x80) ; pad separator
DllCall("ntdll.dll\RtlFillMemoryUlong",UInt,P+N-8,UInt,4,UInt,8*L) ; at end: length in bits < 512 MB
Loop % N//64 {
Loop 16
i := A_Index-1, w%i% := *P | *(P+1)<<8 | *(P+2)<<16 | *(P+3)<<24, P += 4
a := h0, b := h1, c := h2, d := h3
Loop 64 {
i := A_Index-1
If i < 16
f := (b & c) | (~b & d), g := i
Else If i < 32
f := (d & b) | (~d & c), g := 5*i+1 & 15
Else If i < 48
f := b ^ c ^ d, g := 3*i+5 & 15
Else
f := c ^ (b | ~d), g := 7*i & 15
t := d, d := c, c := b
b += rotate(a + f + k%i% + w%g%, r%i%) ; reduced to 32 bits later
a := t
}
h0 := h0+a & y, h1 := h1+b & y, h2 := h2+c & y, h3 := h3+d & y
}
Return hex(h0) . hex(h1) . hex(h2) . hex(h3)
}
rotate(a,b) { ; 32-bit rotate a to left by b bits, bit32..63 garbage
Return a << b | (a & 0xFFFFFFFF) >> (32-b)
}
hex(x) { ; 32-bit little endian hex digits
SetFormat Integer, HEX
x += 0x100000000, x := SubStr(x,-1) . SubStr(x,8,2) . SubStr(x,6,2) . SubStr(x,4,2)
SetFormat Integer, DECIMAL
Return x
}

View file

@ -0,0 +1,19 @@
PRINT FN_MD5("")
PRINT FN_MD5("a")
PRINT FN_MD5("abc")
PRINT FN_MD5("message digest")
PRINT FN_MD5("abcdefghijklmnopqrstuvwxyz")
PRINT FN_MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
PRINT FN_MD5(STRING$(8,"1234567890"))
END
DEF FN_MD5(message$)
LOCAL I%, MD5$, MD5_CTX{}
DIM MD5_CTX{i%(1), buf%(3), in&(63), digest&(15)}
SYS "MD5Init", MD5_CTX{}
SYS "MD5Update", MD5_CTX{}, message$, LEN(message$)
SYS "MD5Final", MD5_CTX{}
FOR I% = 0 TO 15
MD5$ += RIGHT$("0"+STR$~(MD5_CTX.digest&(I%)),2)
NEXT
= MD5$

20
Task/MD5/C++/md5.cpp Normal file
View file

@ -0,0 +1,20 @@
#include <string>
#include <iostream>
#include "Poco/MD5Engine.h"
#include "Poco/DigestStream.h"
using Poco::DigestEngine ;
using Poco::MD5Engine ;
using Poco::DigestOutputStream ;
int main( ) {
std::string myphrase ( "The quick brown fox jumped over the lazy dog's back" ) ;
MD5Engine md5 ;
DigestOutputStream outstr( md5 ) ;
outstr << myphrase ;
outstr.flush( ) ; //to pass everything to the digest engine
const DigestEngine::Digest& digest = md5.digest( ) ;
std::cout << myphrase << " as a MD5 digest :\n" << DigestEngine::digestToHex( digest )
<< " !" << std::endl ;
return 0 ;
}

21
Task/MD5/C/md5-1.c Normal file
View file

@ -0,0 +1,21 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
const char *string = "The quick brown fox jumped over the lazy dog's back";
int main()
{
int i;
unsigned char result[MD5_DIGEST_LENGTH];
MD5(string, strlen(string), result);
// output
for(i = 0; i < MD5_DIGEST_LENGTH; i++)
printf("%02x", result[i]);
printf("\n");
return EXIT_SUCCESS;
}

138
Task/MD5/C/md5-2.c Normal file
View file

@ -0,0 +1,138 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
typedef union uwb {
unsigned w;
unsigned char b[4];
} WBunion;
typedef unsigned Digest[4];
unsigned f0( unsigned abcd[] ){
return ( abcd[1] & abcd[2]) | (~abcd[1] & abcd[3]);}
unsigned f1( unsigned abcd[] ){
return ( abcd[3] & abcd[1]) | (~abcd[3] & abcd[2]);}
unsigned f2( unsigned abcd[] ){
return abcd[1] ^ abcd[2] ^ abcd[3];}
unsigned f3( unsigned abcd[] ){
return abcd[2] ^ (abcd[1] |~ abcd[3]);}
typedef unsigned (*DgstFctn)(unsigned a[]);
unsigned *calcKs( unsigned *k)
{
double s, pwr;
int i;
pwr = pow( 2, 32);
for (i=0; i<64; i++) {
s = fabs(sin(1+i));
k[i] = (unsigned)( s * pwr );
}
return k;
}
// ROtate v Left by amt bits
unsigned rol( unsigned v, short amt )
{
unsigned msk1 = (1<<amt) -1;
return ((v>>(32-amt)) & msk1) | ((v<<amt) & ~msk1);
}
unsigned *md5( const char *msg, int mlen)
{
static Digest h0 = { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476 };
// static Digest h0 = { 0x01234567, 0x89ABCDEF, 0xFEDCBA98, 0x76543210 };
static DgstFctn ff[] = { &f0, &f1, &f2, &f3 };
static short M[] = { 1, 5, 3, 7 };
static short O[] = { 0, 1, 5, 0 };
static short rot0[] = { 7,12,17,22};
static short rot1[] = { 5, 9,14,20};
static short rot2[] = { 4,11,16,23};
static short rot3[] = { 6,10,15,21};
static short *rots[] = {rot0, rot1, rot2, rot3 };
static unsigned kspace[64];
static unsigned *k;
static Digest h;
Digest abcd;
DgstFctn fctn;
short m, o, g;
unsigned f;
short *rotn;
union {
unsigned w[16];
char b[64];
}mm;
int os = 0;
int grp, grps, q, p;
unsigned char *msg2;
if (k==NULL) k= calcKs(kspace);
for (q=0; q<4; q++) h[q] = h0[q]; // initialize
{
grps = 1 + (mlen+8)/64;
msg2 = malloc( 64*grps);
memcpy( msg2, msg, mlen);
msg2[mlen] = (unsigned char)0x80;
q = mlen + 1;
while (q < 64*grps){ msg2[q] = 0; q++ ; }
{
// unsigned char t;
WBunion u;
u.w = 8*mlen;
// t = u.b[0]; u.b[0] = u.b[3]; u.b[3] = t;
// t = u.b[1]; u.b[1] = u.b[2]; u.b[2] = t;
q -= 8;
memcpy(msg2+q, &u.w, 4 );
}
}
for (grp=0; grp<grps; grp++)
{
memcpy( mm.b, msg2+os, 64);
for(q=0;q<4;q++) abcd[q] = h[q];
for (p = 0; p<4; p++) {
fctn = ff[p];
rotn = rots[p];
m = M[p]; o= O[p];
for (q=0; q<16; q++) {
g = (m*q + o) % 16;
f = abcd[1] + rol( abcd[0]+ fctn(abcd) + k[q+16*p] + mm.w[g], rotn[q%4]);
abcd[0] = abcd[3];
abcd[3] = abcd[2];
abcd[2] = abcd[1];
abcd[1] = f;
}
}
for (p=0; p<4; p++)
h[p] += abcd[p];
os += 64;
}
return h;
}
int main( int argc, char *argv[] )
{
int j,k;
const char *msg = "The quick brown fox jumps over the lazy dog.";
unsigned *d = md5(msg, strlen(msg));
WBunion u;
printf("= 0x");
for (j=0;j<4; j++){
u.w = d[j];
for (k=0;k<4;k++) printf("%02x",u.b[k]);
}
printf("\n");
return 0;
}

5
Task/MD5/Clojure/md5.clj Normal file
View file

@ -0,0 +1,5 @@
(apply str
(map (partial format "%02x")
(.digest (doto (java.security.MessageDigest/getInstance "MD5")
.reset
(.update (.getBytes "The quick brown fox jumps over the lazy dog"))))))

View file

@ -0,0 +1,4 @@
(ql:quickload 'ironclad)
(defun md5 (sequence)
(ironclad:byte-array-to-hex-string
(ironclad:digest-sequence :md5 sequence)))

View file

@ -0,0 +1,2 @@
CL-USER> (md5 "The quick brown fox jumped over the lazy dog's back")
"d65474514ed8865634bf8623391fe6d8" ; MD5 hash of the unicode version of the string.

6
Task/MD5/D/md5-1.d Normal file
View file

@ -0,0 +1,6 @@
import std.stdio, std.digest.md;
void main() {
auto txt = "The quick brown fox jumped over the lazy dog's back";
writefln("%-(%02x%)", txt.md5Of());
}

9
Task/MD5/D/md5-2.d Normal file
View file

@ -0,0 +1,9 @@
import tango.io.digest.Md5, tango.io.Stdout;
void main(char[][] args) {
auto md5 = new Md5();
for(int i = 1; i < args.length; i++) {
md5.update(args[i]);
Stdout.formatln("[{}]=>\n[{}]", args[i], md5.hexDigest());
}
}

View file

@ -0,0 +1,27 @@
program MD5Hash;
{$APPTYPE CONSOLE}
uses
SysUtils,
IdHashMessageDigest;
function MD5(aValue: string): string;
begin
with TIdHashMessageDigest5.Create do
begin
Result:= HashStringAsHex(aValue);
Free;
end;
end;
begin
Writeln(MD5(''));
Writeln(MD5('a'));
Writeln(MD5('abc'));
Writeln(MD5('message digest'));
Writeln(MD5('abcdefghijklmnopqrstuvwxyz'));
Writeln(MD5('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'));
Writeln(MD5('12345678901234567890123456789012345678901234567890123456789012345678901234567890'));
Readln;
end.

10
Task/MD5/E/md5.e Normal file
View file

@ -0,0 +1,10 @@
def makeMessageDigest := <import:java.security.makeMessageDigest>
def sprintf := <import:java.lang.makeString>.format
def digest := makeMessageDigest.getInstance("MD5") \
.digest("The quick brown fox jumped over the lazy dog's back".getBytes("iso-8859-1"))
for b in digest {
print(sprintf("%02x", [b]))
}
println()

View file

@ -0,0 +1,7 @@
-module(tests).
-export([md5/1]).
md5(S) ->
string:to_upper(
lists:flatten([io_lib:format("~2.16.0b",[N]) || <<N>> <= erlang:md5(S)])
).

View file

@ -0,0 +1,4 @@
1> c(tests).
{ok,tests}
2> tests:md5("The quick brown fox jumped over the lazy dog's back").
"E38CA1D920C4B8B8D3946B2C72F01680"

18
Task/MD5/Forth/md5.fth Normal file
View file

@ -0,0 +1,18 @@
include ffl/md5.fs
\ Create a MD5 variable md1 in the dictionary
md5-create md1
\ Update the variable with data
s" The quick brown fox jumps over the lazy dog" md1 md5-update
\ Finish the MD5 calculation resulting in four unsigned 32 bit words
\ on the stack representing the hash value
md1 md5-finish
\ Convert the hash value to a hex string and print it
md5+to-string type cr

1
Task/MD5/Frink/md5.frink Normal file
View file

@ -0,0 +1 @@
println[messageDigest["The quick brown fox", "MD5"]]

40
Task/MD5/Go/md5.go Normal file
View file

@ -0,0 +1,40 @@
package main
import (
"crypto/md5"
"fmt"
)
func main() {
for _, p := range [][2]string{
// RFC 1321 test cases
{"d41d8cd98f00b204e9800998ecf8427e", ""},
{"0cc175b9c0f1b6a831c399e269772661", "a"},
{"900150983cd24fb0d6963f7d28e17f72", "abc"},
{"f96b697d7cb7938d525a2f31aaf161d0", "message digest"},
{"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"},
{"d174ab98d277d9f5a5611c2c9f419d9f",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"},
{"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890"},
// test case popular with other RC solutions
{"e38ca1d920c4b8b8d3946b2c72f01680",
"The quick brown fox jumped over the lazy dog's back"},
} {
validate(p[0], p[1])
}
}
var h = md5.New()
func validate(check, s string) {
h.Reset()
h.Write([]byte(s))
sum := fmt.Sprintf("%x", h.Sum(nil))
if sum != check {
fmt.Println("MD5 fail")
fmt.Println(" for string,", s)
fmt.Println(" expected: ", check)
fmt.Println(" got: ", sum)
}
}

View file

@ -0,0 +1,5 @@
import java.security.MessageDigest
String.metaClass.md5Checksum = {
MessageDigest.getInstance('md5').digest(delegate.bytes).collect { String.format("%02x", it) }.join('')
}

View file

@ -0,0 +1 @@
assert 'The quick brown fox jumps over the lazy dog'.md5Checksum() == '9e107d9d372bb6826bd81d3542a419d6'

8
Task/MD5/Haskell/md5.hs Normal file
View file

@ -0,0 +1,8 @@
import Data.Digest.OpenSSL.MD5 (md5sum)
import Data.ByteString (pack)
import Data.Char (ord)
main = do
let message = "The quick brown fox jumped over the lazy dog's back"
digest = (md5sum . pack . map (fromIntegral . ord)) message
putStrLn digest

10
Task/MD5/Icon/md5.icon Normal file
View file

@ -0,0 +1,10 @@
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)
testMD5("", 16rd41d8cd98f00b204e9800998ecf8427e)
end
procedure testMD5(s,rh) # compute the MD5 hash and compare it to reference value
write("Message(length=",*s,") = ",image(s))
write("Digest = ",hexstring(h := MD5(s)),if h = rh then " matches reference hash" else (" does not match reference hash = " || hexstring(rh)),"\n")
end

7
Task/MD5/Io/md5.io Normal file
View file

@ -0,0 +1,7 @@
Io> MD5
==> MD5_0x97663e0:
appendSeq = MD5_appendSeq()
md5 = MD5_md5()
md5String = MD5_md5String()
Io> MD5 clone appendSeq("The quick brown fox jumped over the lazy dog's back") md5String
==> e38ca1d920c4b8b8d3946b2c72f01680

3
Task/MD5/J/md5.j Normal file
View file

@ -0,0 +1,3 @@
require 'convert/misc/md5'
md5 'The quick brown fox jumped over the lazy dog''s back'
e38ca1d920c4b8b8d3946b2c72f01680

28
Task/MD5/Java/md5.java Normal file
View file

@ -0,0 +1,28 @@
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Test MD5 digest computation
*
* @author Roedy Green
* @version 1.0
* @since 2004-06-07
*/
public final class MD5{
public static void main(String[] args) throws UnsupportedEncodingException,
NoSuchAlgorithmException{
byte[] theTextToDigestAsBytes=
"The quick brown fox jumped over the lazy dog's back"
.getBytes("8859_1");
MessageDigest md= MessageDigest.getInstance("MD5");
md.update(theTextToDigestAsBytes);
byte[] digest= md.digest();
// dump out the hash
for(byte b: digest){
System.out.printf("%02X", b & 0xff);
}
System.out.println();
}
}

View file

@ -0,0 +1,145 @@
'[RC]MD5
'from tsh73's January 2008 code
text$="The quick brown fox jumps over the lazy dog"
checkSum$="9e107d9d372bb6826bd81d3542a419d6"
print text$
print checkSum$
test$=md5$(text$)
if test$=checkSum$ then
print "passed"
print test$
else
print "failed"
end if
end
function md5$(text$)
dim r(64)
dim k(64)
dim w(16)
global two32
two32=2^32
'prepare the MD5 checksum table
restore [perRoundShiftAmounts]
for i=0 to 63
read x
r(i)=x
next
'prepare constants
for i=0 to 63
k(i) = int(abs(sin(i+1)) * two32)
next
'initialise variables
h0 = HEXDEC("67452301")
h1 = HEXDEC("EFCDAB89")
h2 = HEXDEC("98BADCFE")
h3 = HEXDEC("10325476")
'find num bits in message
numbits=len(text$)*8
'add bits "10000000"
text$=text$+chr$(128)
'add bits "00000000"
while len(text$) mod 64 <> 56
text$=text$+chr$(0)
wend
'add original length in bits
text$=text$+dec2asc$(numbits)
'MD5 rounds
'process in 64 byte chunks 512bits
for chunk = 1 to len(text$) step 64
chunk$ = mid$(text$, chunk, 64)
for word = 0 TO 15
'invert byte order
b0 = asc(mid$(chunk$, word*4+1, 1))
b1 = asc(mid$(chunk$, word*4+2, 1))
b2 = asc(mid$(chunk$, word*4+3, 1))
b3 = asc(mid$(chunk$, word*4+4, 1))
w(word) = ((b3*256+b2)*256+b1)*256+b0
next word
a = h0
b = h1
c = h2
d = h3
for i = 0 to 63
select case
case 0 <= i and i <= 15
f = (b and c) or (bitNot(b) and d)
g = i
case 16 <= i and i <= 31
f = (d and b) or (bitNot(d) and c)
g = (5 * i + 1) mod 16
case 32 <= i and i <= 47
f = b xor c xor d
g = (3 * i + 5) mod 16
case 48 <= i and i <= 63
f = c xor (b or bitNot(d))
g = (7 * i) mod 16
end select
temp = d
d = c
c = b
b=b+leftrotate(a + f + k(i) + w(g),r(i))
b = b mod two32
a = temp
next i
h0 = (h0 + a) mod two32
h1 = (h1 + b) mod two32
h2 = (h2 + c) mod two32
h3 = (h3 + d) mod two32
next chunk
md5$ = revOrd$(DECHEX$(h0))+_
revOrd$(DECHEX$(h1))+_
revOrd$(DECHEX$(h2))+_
revOrd$(DECHEX$(h3))
[perRoundShiftAmounts]
DATA 7,12,17,22, 7,12,17,22, 7,12,17,22, 7,12,17,22
DATA 5, 9,14,20, 5, 9,14,20, 5, 9,14,20, 5, 9,14,20
DATA 4,11,16,23, 4,11,16,23, 4,11,16,23, 4,11,16,23
DATA 6,10,15,21, 6,10,15,21, 6,10,15,21, 6,10,15,21
end function
' dec2asc: dec to 8 byte asc
function dec2asc$(n)
h$ = ""
for i = 1 to 8
h$ = h$ + chr$(n mod 256)
n = int(n/256)
next
dec2asc$= h$
end function
' bitNot
function bitNot(num)
bitNot = two32 -1 -num
end function
' leftrotate: spins bits left n times
function leftrotate(num,times)
num=num mod two32
r = (num*2^times) mod two32
l = int(num/(2^(32-times)))
leftrotate = r+l
end function
' reverse the HEXDEC$ order
function revOrd$(a$)
a$=left$("00000000", 8-len(a$))+a$
revOrd$ = lower$(mid$(a$,7,2)+mid$(a$,5,2)+mid$(a$,3,2)+mid$(a$,1,2))
end function

16
Task/MD5/Lua/md5.lua Normal file
View file

@ -0,0 +1,16 @@
require "md5"
--printing a sum:
print(md5.sumhexa"The quick brown fox jumps over the lazy dog")
--running the test suite:
local function test(msg,sum) assert(md5.sumhexa(msg)==sum) end
test("","d41d8cd98f00b204e9800998ecf8427e")
test("a","0cc175b9c0f1b6a831c399e269772661")
test("abc","900150983cd24fb0d6963f7d28e17f72")
test("message digest","f96b697d7cb7938d525a2f31aaf161d0")
test("abcdefghijklmnopqrstuvwxyz","c3fcd3d76192e4007dfb496cca67e13b")
test("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789","d174ab98d277d9f5a5611c2c9f419d9f")
test("12345678901234567890123456789012345678901234567890123456789012345678901234567890","57edf4a22be3c955ac49da2e2107b67a")

116
Task/MD5/MATLAB/md5-1.m Normal file
View file

@ -0,0 +1,116 @@
function digest = md5(message)
% digest = md5(message)
% Compute the MD5 digest of the message, as a hexadecimal digest.
% Follow the MD5 algorithm from RFC 1321 [1] and Wikipedia [2].
% [1] http://tools.ietf.org/html/rfc1321
% [2] http://en.wikipedia.org/wiki/MD5
% m is the modulus for 32-bit unsigned arithmetic.
m = 2 ^ 32;
% s is the shift table for circshift(). Each shift is negative
% because it is a left shift.
s = [-7, -12, -17, -22
-5, -9, -14, -20
-4, -11, -16, -23
-6, -10, -15, -21];
% t is the sine table. Each sine is a 32-bit integer, unsigned.
t = floor(abs(sin(1:64)) .* m);
% Initialize the hash, as a row vector of 32-bit integers.
digest = [hex2dec('67452301') ...
hex2dec('EFCDAB89') ...
hex2dec('98BADCFE') ...
hex2dec('10325476')];
% If message contains characters, convert them to ASCII values.
message = double(message);
bytelen = numel(message);
% Pad the message by appending a 1, then appending enough 0s to make
% the bit length congruent to 448 mod 512. Because we have bytes, we
% append 128 '10000000', then append enough 0s '00000000's to make
% the byte length congruent to 56 mod 64.
message = [message, 128, zeros(1, mod(55 - bytelen, 64))];
% Convert the message to 32-bit integers, little endian.
% For little endian, first byte is least significant byte.
message = reshape(message, 4, numel(message) / 4);
message = message(1,:) + ... % least significant byte
message(2,:) * 256 + ...
message(3,:) * 65536 + ...
message(4,:) * 16777216; % most significant byte
% Append the bit length as a 64-bit integer, little endian.
bitlen = bytelen * 8;
message = [message, mod(bitlen, m), mod(bitlen / m, m)];
% Process each 512-bit block. Because we have 32-bit integers, each
% block has 16 elements, message(k + (0:15)).
for k = 1:16:numel(message)
% Copy hash.
a = digest(1); b = digest(2); c = digest(3); d = digest(4);
% Do 64 operations.
for i = (1:64)
% Convert b, c, d to row vectors of bits (0s and 1s).
bv = dec2bin(b, 32) - '0';
cv = dec2bin(c, 32) - '0';
dv = dec2bin(d, 32) - '0';
% Find f = mix of b, c, d.
% ki = index in 0:15, to message(k + ki).
% sr = row in 1:4, to s(sr, :).
if i <= 16 % Round 1
f = (bv & cv) | (~bv & dv);
ki = i - 1;
sr = 1;
elseif i <= 32 % Round 2
f = (bv & dv) | (cv & ~dv);
ki = mod(5 * i - 4, 16);
sr = 2;
elseif i <= 48 % Round 3
f = xor(bv, xor(cv, dv));
ki = mod(3 * i + 2, 16);
sr = 3;
else % Round 4
f = xor(cv, bv | ~dv);
ki = mod(7 * i - 7, 16);
sr = 4;
end
% Convert f, from row vector of bits, to 32-bit integer.
f = bin2dec(char(f + '0'));
% Do circular shift of sum.
sc = mod(i - 1, 4) + 1;
sum = mod(a + f + message(k + ki) + t(i), m);
sum = dec2bin(sum, 32);
sum = circshift(sum, [0, s(sr, sc)]);
sum = bin2dec(sum);
% Update a, b, c, d.
temp = d;
d = c;
c = b;
b = mod(b + sum, m);
a = temp;
end %for i
% Add hash of this block to hash of previous blocks.
digest = mod(digest + [a, b, c, d], m);
end %for k
% Convert hash from 32-bit integers, little endian, to bytes.
digest = [digest % least significant byte
digest / 256
digest / 65536
digest / 16777216]; % most significant byte
digest = reshape(mod(floor(digest), 256), 1, numel(digest));
% Convert hash to hexadecimal.
digest = dec2hex(digest);
digest = reshape(transpose(digest), 1, numel(digest));
end %md5

2
Task/MD5/MATLAB/md5-2.m Normal file
View file

@ -0,0 +1,2 @@
octave:14> md5('Rosetta Code')
ans = CCA1BF66B09554E10F837838C3D3EFB1

2
Task/MD5/MOO/md5.moo Normal file
View file

@ -0,0 +1,2 @@
string = "The quick brown fox jumped over the lazy dog's back";
player:tell(string_hash(string));

View file

@ -0,0 +1,7 @@
StringHash[string_String]:=Module[{stream=OpenWrite[],file,hash},
WriteString[stream,string];
file=Close[stream];
hash=FileHash[file,"MD5"];
DeleteFile[file];
hash
]

View file

@ -0,0 +1 @@
StringHash["The quick brown fox jumped over the lazy dog's back"] // BaseForm[#, 16] &

View file

@ -0,0 +1 @@
e38ca1d920c4b8b8d3946b2c72f01680

2
Task/MD5/PHP/md5.php Normal file
View file

@ -0,0 +1,2 @@
$string = "The quick brown fox jumped over the lazy dog's back";
echo md5( $string );

3
Task/MD5/Perl/md5-1.pl Normal file
View file

@ -0,0 +1,3 @@
use Digest::MD5 qw(md5_hex);
print md5_hex("The quick brown fox jumped over the lazy dog's back"), "\n";

5
Task/MD5/Perl/md5-2.pl Normal file
View file

@ -0,0 +1,5 @@
use Digest::MD5;
$md5 = Digest::MD5->new;
$md5->add("The quick brown fox jumped over the lazy dog's back");
print $md5->hexdigest, "\n";

4
Task/MD5/PicoLisp/md5.l Normal file
View file

@ -0,0 +1,4 @@
(let Str "The quick brown fox jumped over the lazy dog's back"
(pack
(mapcar '((B) (pad 2 (hex B)))
(native "libcrypto.so" "MD5" '(B . 16) Str (length Str) '(NIL (16))) ) ) )

13
Task/MD5/Python/md5-1.py Normal file
View file

@ -0,0 +1,13 @@
>>> import hashlib
>>> # RFC 1321 test suite:
>>> tests = (
(b"", 'd41d8cd98f00b204e9800998ecf8427e'),
(b"a", '0cc175b9c0f1b6a831c399e269772661'),
(b"abc", '900150983cd24fb0d6963f7d28e17f72'),
(b"message digest", 'f96b697d7cb7938d525a2f31aaf161d0'),
(b"abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b'),
(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f'),
(b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a') )
>>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden
>>>

3
Task/MD5/Python/md5-2.py Normal file
View file

@ -0,0 +1,3 @@
>>> import hashlib
>>> print hashlib.md5("The quick brown fox jumped over the lazy dog's back").hexdigest()
e38ca1d920c4b8b8d3946b2c72f01680

3
Task/MD5/Python/md5-3.py Normal file
View file

@ -0,0 +1,3 @@
>>> import md5
>>> print md5.md5("The quick brown fox jumped over the lazy dog's back").hexdigest()
e38ca1d920c4b8b8d3946b2c72f01680

3
Task/MD5/R/md5.r Normal file
View file

@ -0,0 +1,3 @@
library(digest)
hexdigest <- digest("The quick brown fox jumped over the lazy dog's back",
algo="md5", serialize=FALSE)

124
Task/MD5/REXX/md5.rexx Normal file
View file

@ -0,0 +1,124 @@
/*REXX program to test the MD5 procedure as per the test suite in the */
/* IETF RFC (1321) ─── The MD5 Message─Digest Algorithm. April 1992. */
/*─────────────────────────────────────Md5 test suite (from above doc). */
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*/
$=!||'80'x||copies('0'x,plus%8-1)reverse(right(d2c(8*#),4,'0'x))||'00000000'x
do j=0 to length($)%64-1 /*process message (lots of steps)*/
a_=a; b_=b; c_=c; d_=d
chunk=j*64
do k=1 for 16 /*process the message in chunks. */
!.k=reverse(substr($,chunk+1+4*(k-1),4))
end /*k*/
a=.part1(a,b,c,d, 0, 7,3614090360) /* 1*/
d=.part1(d,a,b,c, 1,12,3905402710) /* 2*/
c=.part1(c,d,a,b, 2,17, 606105819) /* 3*/
b=.part1(b,c,d,a, 3,22,3250441966) /* 4*/
a=.part1(a,b,c,d, 4, 7,4118548399) /* 5*/
d=.part1(d,a,b,c, 5,12,1200080426) /* 6*/
c=.part1(c,d,a,b, 6,17,2821735955) /* 7*/
b=.part1(b,c,d,a, 7,22,4249261313) /* 8*/
a=.part1(a,b,c,d, 8, 7,1770035416) /* 9*/
d=.part1(d,a,b,c, 9,12,2336552879) /*10*/
c=.part1(c,d,a,b,10,17,4294925233) /*11*/
b=.part1(b,c,d,a,11,22,2304563134) /*12*/
a=.part1(a,b,c,d,12, 7,1804603682) /*13*/
d=.part1(d,a,b,c,13,12,4254626195) /*14*/
c=.part1(c,d,a,b,14,17,2792965006) /*15*/
b=.part1(b,c,d,a,15,22,1236535329) /*16*/
a=.part2(a,b,c,d, 1, 5,4129170786) /*17*/
d=.part2(d,a,b,c, 6, 9,3225465664) /*18*/
c=.part2(c,d,a,b,11,14, 643717713) /*19*/
b=.part2(b,c,d,a, 0,20,3921069994) /*20*/
a=.part2(a,b,c,d, 5, 5,3593408605) /*21*/
d=.part2(d,a,b,c,10, 9, 38016083) /*22*/
c=.part2(c,d,a,b,15,14,3634488961) /*23*/
b=.part2(b,c,d,a, 4,20,3889429448) /*24*/
a=.part2(a,b,c,d, 9, 5, 568446438) /*25*/
d=.part2(d,a,b,c,14, 9,3275163606) /*26*/
c=.part2(c,d,a,b, 3,14,4107603335) /*27*/
b=.part2(b,c,d,a, 8,20,1163531501) /*28*/
a=.part2(a,b,c,d,13, 5,2850285829) /*29*/
d=.part2(d,a,b,c, 2, 9,4243563512) /*30*/
c=.part2(c,d,a,b, 7,14,1735328473) /*31*/
b=.part2(b,c,d,a,12,20,2368359562) /*32*/
a=.part3(a,b,c,d, 5, 4,4294588738) /*33*/
d=.part3(d,a,b,c, 8,11,2272392833) /*34*/
c=.part3(c,d,a,b,11,16,1839030562) /*35*/
b=.part3(b,c,d,a,14,23,4259657740) /*36*/
a=.part3(a,b,c,d, 1, 4,2763975236) /*37*/
d=.part3(d,a,b,c, 4,11,1272893353) /*38*/
c=.part3(c,d,a,b, 7,16,4139469664) /*39*/
b=.part3(b,c,d,a,10,23,3200236656) /*40*/
a=.part3(a,b,c,d,13, 4, 681279174) /*41*/
d=.part3(d,a,b,c, 0,11,3936430074) /*42*/
c=.part3(c,d,a,b, 3,16,3572445317) /*43*/
b=.part3(b,c,d,a, 6,23, 76029189) /*44*/
a=.part3(a,b,c,d, 9, 4,3654602809) /*45*/
d=.part3(d,a,b,c,12,11,3873151461) /*46*/
c=.part3(c,d,a,b,15,16, 530742520) /*47*/
b=.part3(b,c,d,a, 2,23,3299628645) /*48*/
a=.part4(a,b,c,d, 0, 6,4096336452) /*49*/
d=.part4(d,a,b,c, 7,10,1126891415) /*50*/
c=.part4(c,d,a,b,14,15,2878612391) /*51*/
b=.part4(b,c,d,a, 5,21,4237533241) /*52*/
a=.part4(a,b,c,d,12, 6,1700485571) /*53*/
d=.part4(d,a,b,c, 3,10,2399980690) /*54*/
c=.part4(c,d,a,b,10,15,4293915773) /*55*/
b=.part4(b,c,d,a, 1,21,2240044497) /*56*/
a=.part4(a,b,c,d, 8, 6,1873313359) /*57*/
d=.part4(d,a,b,c,15,10,4264355552) /*58*/
c=.part4(c,d,a,b, 6,15,2734768916) /*59*/
b=.part4(b,c,d,a,13,21,1309151649) /*60*/
a=.part4(a,b,c,d, 4, 6,4149444226) /*61*/
d=.part4(d,a,b,c,11,10,3174756917) /*62*/
c=.part4(c,d,a,b, 2,15, 718787259) /*63*/
b=.part4(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 c2x(reverse(a))c2x(reverse(b))c2x(reverse(c))c2x(reverse(d))
/*─────────────────────────────────────subroutines──────────────────────*/
.part1: 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)
.part2: 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)
.part3: 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)
.part4: 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)+arg(7)),4,'0'x),m),x)
.h: procedure; parse arg x,y,z; return bitxor(bitxor(x,y),z)
.i: return bitxor(arg(2),bitor(arg(1),bitxor(arg(3),'ffffffff'x)))
.a: return right(d2c(c2d(arg(1))+c2d(arg(2))),4,'0'x)
.f: procedure; parse arg x,y,z
return bitor(bitand(x,y),bitand(bitxor(x,'ffffffff'x),z))
.g: procedure; parse arg x,y,z
return bitor(bitand(x,z),bitand(y,bitxor(z,'ffffffff'x)))
.lR: procedure; parse arg _,#; if #==0 then return _ /*left rotate.*/
?=x2b(c2x(_)); return x2c(b2x(right(?||left(?,#),length(?))))

10
Task/MD5/Racket/md5.rkt Normal file
View file

@ -0,0 +1,10 @@
#lang racket
(require file/md5)
(md5 "")
(md5 "a")
(md5 "abc")
(md5 "message digest")
(md5 "abcdefghijklmnopqrstuvwxyz")
(md5 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
(md5 "12345678901234567890123456789012345678901234567890123456789012345678901234567890")

3
Task/MD5/Ruby/md5.rb Normal file
View file

@ -0,0 +1,3 @@
require 'digest'
Digest::MD5.hexdigest("The quick brown fox jumped over the lazy dog's back")
# => "e38ca1d920c4b8b8d3946b2c72f01680"

7
Task/MD5/Scala/md5.scala Normal file
View file

@ -0,0 +1,7 @@
def MD5( s:String ) : String = {
// Besides "MD5", "SHA-256", and other hashes are available
val m = java.security.MessageDigest.getInstance("MD5").digest(s.getBytes("UTF-8"));
m map {c => (c & 0xff) toHexString} mkString
}
MD5("The quick brown fox jumped over the lazy dog's back")

View file

@ -0,0 +1,2 @@
PackageLoader fileInPackage: 'Digest' !
(MD5 hexDigestOf: 'The quick brown fox jumped over the lazy dog''s back') displayNl.

View file

@ -0,0 +1 @@
(MD5Stream hashValueOf: 'The quick brown fox jumped over the lazy dog''s back') printCR.

3
Task/MD5/Tcl/md5.tcl Normal file
View file

@ -0,0 +1,3 @@
package require md5
puts [md5::md5 -hex "The quick brown fox jumped over the lazy dog's back"]
# ==> E38CA1D920C4B8B8D3946B2C72F01680