Skip to content

Instantly share code, notes, and snippets.

@Higgs1
Last active August 29, 2015 14:17
Show Gist options
  • Save Higgs1/08ec61fbb250c1c92151 to your computer and use it in GitHub Desktop.
Save Higgs1/08ec61fbb250c1c92151 to your computer and use it in GitHub Desktop.
CoffeeScript Simple MD5
# 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 ''
@Higgs1
Copy link
Author

Higgs1 commented Mar 21, 2015

This isn't meant to be a fast MD5 implementation, but it's meant to have a smaller code size than implementations that have precomputed the main loop, while also trying to be simple. It follows the wikipedia page a little too.
This implementation also doesn't support streaming, but I might make another version in the future that does, with the same method names as Python's MD5.

@Higgs1
Copy link
Author

Higgs1 commented Mar 22, 2015

To get the hex encoded value, check out my hex codec functions for CoffeeScript.

@Higgs1
Copy link
Author

Higgs1 commented Mar 22, 2015

And be sure to encode strings into byte strings first! Use my UTF-8 codec functions for CoffeeScript.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment