Cryptography

The MD2 Message-Digest Algorithm

Step 1. Append Padding Bytes

The message is "padded" (extended) so that its length (in bytes) is congruent to 0, modulo 16. That is, the message is extended so that it is a multiple of 16 bytes long. Padding is always performed, even if the length of the message is already congruent to 0, modulo 16.

Padding is performed as follows: "i" bytes of value "i" are appended to the message so that the length in bytes of the padded message becomes congruent to 0, modulo 16. At least one byte and at most 16 bytes are appended.

At this point the resulting message (after padding with bytes) has a length that is an exact multiple of 16 bytes. Let M[0 ... N-1] denote the bytes of the resulting message, where N is a multiple of 16.

Step 2. Append Checksum

A 16-byte checksum of the message is appended to the result of the previous step.

This step uses a 256-byte "random" permutation constructed from the digits of pi. Let S[i] denote the i-th element of this table. The table is given in the appendix.

Do the following:

/* Clear checksum. */
For i ← 0 TO 15
    C[i] ← 0
NEXT i
L ← 0.
/* Process each 16-word block. */
block ← N / 16
For i ← 0 To block - 1
    /* Checksum block i. */
    For j ← 0 to 15
        c ← M[i * 16 + j].
        C[j] ← S[c xor L].
        L ← C[j].
    NEXT j
NEXT i

The 16-byte checksum C[0 ... 15] is appended to the message.

Step 3. Initialize MD Buffer

A 48-byte buffer X is used to compute the message digest. The buffer is initialized to zero.

Step 4. Process Message in 16-Byte Blocks

This step uses the same 256-byte permutation S as step 2 does.

Do the following:

/* Process each 16-word block. */
For i ← 0 TO block - 1
    /* Copy block i into X. */
    For j ← 0 TO 15
        X[16 + j] ← M[i * 16 + j].
        X[32 + j] ← (X[16 + j] xor X[j]).
    NEXT j
    t ← 0.
    /* Do 18 rounds. */
    For j ← 0 TO 17
        /* Round j. */
        For k = 0 to 47 do
            t ← X[k] ← (X[k] xor S[t]).
        NEXT k
        t ← (t + j) modulo 256.
    NEXT j
NEXT i

Step 5. Output

The message digest produced as output is X[0 ... 15]. That is, we begin with X[0], and end with X[15].

S-BOX

012345678910111213141516171819
04146672011622161241615484161236240619981675243
20192199115140152147432171887613020230155876025321222422
40103661112413823229181907819621421815822273160251245142
6018747238122169104121145211787631481941613711349533
8012812793154901445039536220423119124715132552548179
100721651812092159414642172861701987918456210150164125182
120118252107226156116424169157112891001131353213491207101
140230451682279637173174176185246287097105526412615
16085711633522181175581959224920618619723438448313110
18013340132921122320524465129778210622055200108193171250
200362251238121891777412013614913922799232109233203213254
220590295724223918314102882082281661191142482351177510