;One crypto-cycle (Cycle j1):
;In: i = temp (cycle number)
; L = @_N1
; R = @_N2
;Out: RES = @RES
Crypto: ldx MKey
clr tempH
lsl temp ;temp * 2
lsl temp ;temp * 2
add XL,temp
adc XH,tempH ;X - pointer to MKey
;res = _n1 + MKey[i]
ldy Res
ldz _n1
ld temp,Z+
ld tempL,X+
add temp,tempL
st Y+,temp
ld temp,Z+
ld tempL,X+
adc temp,tempL
st Y+,temp
ld temp,Z+
ld tempL,X+
adc temp,tempL
st Y+,temp
ld temp,Z+
ld tempL,X+
adc temp,tempL
st Y+,temp
;for(Cnt = 0; Cnt < 8; Cnt++)
ldy Res
ldi Cnt,0
;temp = res >> (4 * Cnt) & 0x0F
XLat: ld temp,Y
sbrc Cnt,0
swap temp
mov XL,temp
andi temp,0x0F
;temp = RTable[Cnt][temp]
table RTable
mov tempL,Cnt
lsl tempL ;tempL * 2
lsl tempL ;tempL * 2
lsl tempL ;tempL * 2
lsl tempL ;tempL * 2
add temp,tempL ;C = 0
mov tempL,temp
ror temp
add ZL,temp
adc ZH,tempH
lpm temp,Z
sbrc tempL,0
swap temp
andi temp,0x0F
;res = res & (0x0F << (4 * Cnt)) | (temp << (4 * Cnt))
andi XL,0xF0
or temp,XL
sbrc Cnt,0
swap temp
st Y,temp
sbrc Cnt,0
adiw YH:YL,1
inc Cnt
cpi Cnt,8
brne XLat
;r7:r6:r5:r4 = res rol 8
ldy Res
ld r5,Y+
ld r6,Y+
ld r7,Y+
ld r4,Y+
;r7:r6:r5:r4 = r7:r6:r5:r4 rol 3
ldi Cnt,3
rol3: mov temp,r7
rol temp
rol r4
rol r5
rol r6
rol r7
dec Cnt
brne rol3
;res = r7:r6:r5:r4 ^ _n2
ldx _n2
ldy Res
ld temp,X+
eor temp,r4
st Y+,temp
ld temp,X+
eor temp,r5
st Y+,temp
ld temp,X+
eor temp,r6
st Y+,temp
ld temp,X+
eor temp,r7
st Y+,temp
ret
;32 crypto cycles (Cycle 32-encryption):
;In: @_N1
; @_N2
;Out: @_N1
; @_N2
Crypt32:
clr Cnt1
Iter1: mov temp,Cnt1
rcall Crypto
ldx _n2
ldy _n1
rcall Mov32
ldx _n1
ldy Res
rcall Mov32
inc Cnt1
cpi Cnt1,8
brne iter1
clr Cnt1
Iter2: mov temp,Cnt1
rcall Crypto
ldx _n2
ldy _n1
rcall Mov32
ldx _n1
ldy Res
rcall Mov32
inc Cnt1
cpi Cnt1,8
brne iter2
clr Cnt1
Iter3: mov temp,Cnt1
rcall Crypto
ldx _n2
ldy _n1
rcall Mov32
ldx _n1
ldy Res
rcall Mov32
inc Cnt1
cpi Cnt1,8
brne iter3
ldi Cnt1,7
Iter4: mov temp,Cnt1
rcall Crypto
ldx _n2
ldy _n1
rcall Mov32
ldx _n1
ldy Res
rcall Mov32
dec Cnt1
brne iter4
clr temp
rcall Crypto
ldx _n2
ldy Res
rcall Mov32
ret
;Moves 32-bit value
;@X = @Y
;In: XH:XL - destination
; YH:YL - source
Mov32: ldi Cnt,4
Mv: ld temp,Y+
st X+,temp
dec Cnt
brne Mv
ret