SK..R1 integrity bytes do not match the value in SKR1 Integrity tag

Hi

I am trying to implement D Function in python.

import hashlib

from Crypto.Cipher import AES
from Crypto.Hash import SHA
from Crypto.Util.Padding import pad as padding
from Crypto.PublicKey import RSA

PRIME = 813416437
NB_RD = 16

def dfunction(R2, ASk):
    tmp = bytearray(20)
    pad = bytearray(64)
    MBlock = [0] * 14
    P = PRIME

    if len(R2) >= 56:
        return -1  # kDRMSKDServerParamErr

    # Padding until a multiple of 56B
    pad[:len(R2)] = R2
    pad[len(R2)] = 0x80
    pad[len(R2) + 1:56] = [0] * (56 - len(R2) - 1)

    # Create 14 32b values
    for i in range(14):
        MBlock[i] = (pad[4 * i] << 24) ^ (pad[4 * i + 1] << 16) ^ (pad[4 * i + 2] << 8) ^ pad[4 * i + 3]

    # Reunify into 2 32 bits values
    #MBlock[0] += sum(MBlock[1:7])
    #MBlock[1] = 0
    #MBlock[1] += sum(MBlock[7:])

    # Reunify into 2 32 bits values
    for i in range(1, 7):
        MBlock[0] += MBlock[i]

    MBlock[1] = 0
    for i in range(7):
        MBlock[1] += MBlock[i + 7]

    # Apply the function (C_r)
    for i in range(2):
        for r in range(NB_RD):
            if MBlock[i] & 1:
                MBlock[i] >>= 1
            else:
                MBlock[i] = (3 * MBlock[i] + 1) % P

    # Append to M
    for i in range(4):
        pad[56 + i] = (MBlock[0] >> (8 * i)) & 0xFF
        pad[60 + i] = (MBlock[1] >> (8 * i)) & 0xFF

    h = hashlib.sha1()
    h.update(pad)

    hh = h.digest()[:16]
    cipher = AES.new(ASk, AES.MODE_ECB)
    DASk = cipher.encrypt(padding(hh, AES.block_size))
    return DASk

Then, i am trying to match integrities and they does not match. I think there is an mistake in D Function implementation. Any clue whats wrong?

Thank you

SK..R1 integrity bytes do not match the value in SKR1 Integrity tag
 
 
Q