PDA

View Full Version : XTEA Encrypt Decrypt Routines



Ron Marcus
- 3rd May 2008, 15:38
Here is a set of subroutines for encoding and decoding RF transmissions using PIC18s and PBP2.50a. Originally I posted in off topic, but it was suggested to move it here. I hope someone can use it.
Ron


;************************************************* *********************
; XTEA VARIABLES ************************************************** ***
;************************************************* *********************
roundin con 32 ;number of loops
Delta con $9E3779B9 ;5/4/2 * 2power32 (big-ss number!)

round var byte
Sumin var long
vy var Long
text_byte var byte[8] ;text coming in, going out.Eight bytes at a time. If less,you must pad it to be 8 bytes long.

vz var Long
tb var byte
Sum var long
temp var long
tmp0 var temp.byte0
tmp1 var temp.byte1
tmp2 var temp.byte2
tmp3 var temp.byte3
key var long[4]
ka var key[0]

kb var key[1]
kc var key[2]
kd var key[3]
limit var long
block var long[2]
index var word
key[0] = $31323334 ;128 bit key
key[1] = $93D8E9AF ;don't use mine
key[2] = $275FC2BA ;must be
key[3] = $95E20110 ;random


;************************************************* *********************



main:



hserout [str text_byte\8,13] ;the unchanged block of 8 bytes
gosub beep
;pause 1000
GOsub TEAenc ;scramble well
hserout [str text_byte\8,13] ;show mess
gosub teadec ;unscramble
hserout [str text_byte\8,13] ;No s--t, it works!
pause 100
stop
TEAenc: for tb = 0 to 3 ; convert string into code
vy.byte0[tb] = text_byte[tb]
vz.byte0[tb] = text_byte[tb+4]
next tb
sum = 0
Limit = Delta * roundin
while Sum <> limit
vy = vy + (((vz<<4) ^ (vz >>5))^(Sum + Key[sum & 3]))
sum = sum + Delta
vz = vz + (((vy<<4) ^ (vy >>5))^(Sum + Key[sum>>11 & 3]))
wend
for tb = 0 to 3
text_byte[tb]= vy.byte0[tb]
text_byte[tb+4] = vz.byte0[tb]
next tb
return

;************************************************* **************************
TEAdec: ;Convert code into string
for tb = 0 to 3
vy.byte0[tb] = text_byte[tb]
vz.byte0[tb] = text_byte[tb+4]
next tb

sum = Delta * roundin
while sum <> 0
vz = vz - (((vy<<4) ^ (vy >>5))^(Sum + Key[(sum>>11) & 3]))
sum = sum - Delta
vy = vy - (((vz<<4) ^ (vz >>5))^(Sum + Key[sum & 3]))
wend
for tb = 0 to 3
text_byte[tb]= vy.byte0[tb]
text_byte[tb+4] = vz.byte0[tb]
next tb
return