;(C)2005 wek http://www.efton.sk ;Free for personal use. ;For commercial use contact wek@efton.sk ;Implements the modified TEA algorithm by Needham&Wheeler in any '51 compatible mcu ;uses r0,r4,r5,r6,r7,dptr ;uses r2 as round counter ; ;6952 cycles including ret ;0DAh=218 bytes including 16 bytes of key ;round: ; y += (((z << 4) ^ (z >> 5) + z) ^ (sum + k[sum&3]) ; sum += delta; ; z += (((y << 4) ^ (y >> 5) + y) ^ (sum + k[sum>>11 & 3]) ; ; ; ;Key can be also in IRAM or XRAM; needs some modification for this. ;IRAM is easy; simply add Key to r0 after calculating offset and replace mov a,r0; movc a,@a+dptr by mov a,@r0. ;XRAM is slightly more complicated, the complete pointer should be calculated to dptr ; (or the 8-bit movc a,@r0 shall be used, with p2 properly set; but only if the whole key does not cross the 256-byte boundary...) ; ; DSEG AT 30h y0: DS 1 y1: DS 1 y2: DS 1 y3: DS 1 z0: DS 1 z1: DS 1 z2: DS 1 z3: DS 1 tmp0: DS 1 tmp1: DS 1 tmp2: DS 1 tmp3: DS 1 sum0: DS 1 sum1: DS 1 sum2: DS 1 sum3: DS 1 CSEG XTea: clr a mov sum0,a ;sum = 0 mov sum1,a mov sum2,a mov sum3,a mov r2,#32*2 ;nr of rounds *2 (because of trick with twice the main code, one for y and one for z; and another inside...) mov dptr,#key ;dptr will not change TeaRound: mov r4,z0 mov r5,z1 mov r6,z2 mov r7,z3 TeaSubRound: mov r0,#tmp3 ;tmp = z << 4 mov a,r7 swap a mov @r0,a ;@r0=tmp3 mov a,r6 swap a xchd a,@r0 ;@r0=tmp3 dec r0 mov @r0,a ;@r0=tmp2 mov a,r5 swap a xchd a,@r0 ;@r0=tmp2 dec r0 mov @r0,a ;@r0=tmp1 mov a,r4 swap a xchd a,@r0 ;@r0=tmp1 mov tmp0,a anl tmp0,#0F0h rrc a ;tmp ^= z >> 5 anl a,#07h xrl a,tmp3 xch a,tmp3 rrc a xrl a,tmp2 xch a,tmp2 rrc a xrl a,@r0 ;tmp1 xch a,@r0 ;tmp1 rrc a xrl a,tmp0 add a,r4 ;z = z+tmp mov r4,a mov a,r5 addc a,tmp1 mov r5,a mov a,r6 addc a,tmp2 mov r6,a mov a,r7 addc a,tmp3 mov r7,a mov a,r2 jb acc.0,TeaX1 mov a,sum0 ;r0 = [sum&3] rl a rl a sjmp TeaX2 TeaX1: mov a,sum1 ;r0 = [sum>>11&3] rr a TeaX2: anl a,#0Ch mov r0,a movc a,@a+dptr ;result ^= sum + k[pointer] inc r0 add a,sum0 xrl a,r4 mov r4,a mov a,r0 movc a,@a+dptr inc r0 addc a,sum1 xrl a,r5 mov r5,a mov a,r0 movc a,@a+dptr inc r0 addc a,sum2 xrl a,r6 mov r6,a mov a,r0 movc a,@a+dptr addc a,sum3 xrl a,r7 mov r7,a dec r2 mov a,r2 jb acc.0,TeaSubRound2 mov a,r4 add a,z0 mov z0,a mov a,r5 addc a,z1 mov z1,a mov a,r6 addc a,z2 mov z2,a mov a,r7 addc a,z3 mov z3,a cjne r2,#0,TeaRoundA ret TeaRoundA: jmp TeaRound TeaSubRound2: mov a,r4 add a,y0 mov y0,a mov r4,a mov a,r5 addc a,y1 mov y1,a mov r5,a mov a,r6 addc a,y2 mov y2,a mov r6,a mov a,r7 addc a,y3 mov y3,a mov r7,a mov a,sum0 ;sum += delta add a,#0B9h ;delta[0] mov sum0,a mov a,sum1 addc a,#079h ;delta[1] mov sum1,a mov a,sum2 addc a,#037h ;delta[2] mov sum2,a mov a,sum3 addc a,#09Eh ;delta[3] mov sum3,a jmp TeaSubRound Key: db 000h,000h,000h,000h db 000h,000h,000h,000h db 000h,000h,000h,000h db 000h,000h,000h,000h end