(bytes)
| 30 | * @return {Uint8Array} Md5 message digest |
| 31 | */ |
| 32 | export default function md5 (bytes) { |
| 33 | // make array mutable |
| 34 | bytes = Array.from(bytes) |
| 35 | |
| 36 | // track number of bytes before preprocessing |
| 37 | const b = bytes.length |
| 38 | |
| 39 | // RFC 1321 3.1: Step 1. Append Padding Bits |
| 40 | |
| 41 | // append a single "1" bit to the message |
| 42 | // it's okay to add a whole byte, because it gets padded anyway |
| 43 | bytes.push(0b10000000) |
| 44 | |
| 45 | // "0" bits are appended so that the length in bits of the padded message |
| 46 | // becomes congruent to 448 (56 bytes), modulo 512 (64 bytes) |
| 47 | while (bytes.length % 64 !== 56) { |
| 48 | bytes.push(0x00) |
| 49 | } |
| 50 | |
| 51 | // RFC 1321 3.2 Step 2. Append Length |
| 52 | |
| 53 | // append the low-order 64 bits of b modulo 2^64 to bytes |
| 54 | // these bits are appended as two 32-bit words, appended low-order word first |
| 55 | let shift |
| 56 | for (let i = 0; i < 8; i++) { |
| 57 | if (i === 0) { |
| 58 | // multiply bytes by 8 (left shift by 3 bits) |
| 59 | bytes.push((b & 0b11111) << 3) |
| 60 | } else { |
| 61 | // limit right shift to 31 bits |
| 62 | shift = i * 8 - 3 |
| 63 | bytes.push(shift < 32 ? (b >> shift) & 0xff : 0) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | // let m denote the words of the resulting message |
| 68 | const n = bytes.length / 4 |
| 69 | const m = new Array(n) |
| 70 | |
| 71 | for (let i = 0; i < n; i++) { |
| 72 | // each consecutive group of four bytes is interpreted as a word with the |
| 73 | // low-order (least significant) byte given first |
| 74 | m[i] = |
| 75 | (bytes[i * 4 + 3] << 24) + |
| 76 | (bytes[i * 4 + 2] << 16) + |
| 77 | (bytes[i * 4 + 1] << 8) + |
| 78 | bytes[i * 4] |
| 79 | } |
| 80 | |
| 81 | // RFC 1321 3.3: Step 3. Initialize MD Buffer |
| 82 | |
| 83 | // load magic initialization constants A, B, C & D |
| 84 | const context = [IA, IB, IC, ID] |
| 85 | |
| 86 | // RFC 1321 3.4 Step 4. Process Message in 16-Word Blocks |
| 87 | for (let i = 0; i < n; i += 16) { |
| 88 | md5Transform(context, m.slice(i, i + 16)) |
| 89 | } |
no test coverage detected