Keeloq的python实现

KeeLoq_NLF = 0x3A5C742E

def bit(x,n):

    x = (((x)>>(n))&1)

    return x

 

def g5(x,a,b,c,d,e):

    y = (bit(x,a) + bit(x,b)*2 + bit(x,c)*4 + bit(x,d)*8 + bit(x,e)*16)

    return y

 

def Keeloq_Encrypt(data,key):

    x = int(data)

    for i in range(528):

        x = (x>>1) ^ ((bit(x,0) ^ bit(x,16) ^ bit(key,i&63) ^ bit(KeeLoq_NLF,g5(x,1,9,20,26,31)))<<31);

    return x

 

def Keeloq_Decrypt(data,key):

    x = int(data)

    for i in range(528):

        x = int(x<<1) ^ bit(x,31) ^ bit(x,15) ^ bit(key,(15-i)&63) ^ bit(KeeLoq_NLF,g5(x,0,8,19,25,30))

    return x

 

cmd = 0

while(cmd != 3):

    try:

        cmd = input("Please select the function \n 1:Keeloq Encrypt\n 2:Keeloq Decrypt\n 3:Quit\n select:")

        if cmd == 1:

            data1 = input("Please input data for Keeloq Encrypt:")

            Sk = input("Please input Sk:")

            result = Keeloq_Encrypt(data1,Sk)

            print('\nResult = %x\n'%result)

        if cmd == 2:

            data1 = input("Please input data for Keeloq Decrypt:")

            Sk = input("Please input Sk:")

            result = Keeloq_Decrypt(data1,Sk) & 0xFFFFFFFF

            print('\nResult = %x\n'%result)

    except:

        pass

print('End')

posted @ 2018-03-03 08:50  DracoW  阅读(398)  评论(0编辑  收藏  举报