1// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5/*
6	Implementation adapted from Needham and Wheeler's paper:
7	http://www.cix.co.uk/~klockstone/xtea.pdf
8
9	A precalculated look up table is used during encryption/decryption for values that are based purely on the key.
10*/
11
12package xtea
13
14// XTEA is based on 64 rounds.
15const numRounds = 64
16
17// blockToUint32 reads an 8 byte slice into two uint32s.
18// The block is treated as big endian.
19func blockToUint32(src []byte) (uint32, uint32) {
20	r0 := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3])
21	r1 := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7])
22	return r0, r1
23}
24
25// uint32ToBlock writes two uint32s into an 8 byte data block.
26// Values are written as big endian.
27func uint32ToBlock(v0, v1 uint32, dst []byte) {
28	dst[0] = byte(v0 >> 24)
29	dst[1] = byte(v0 >> 16)
30	dst[2] = byte(v0 >> 8)
31	dst[3] = byte(v0)
32	dst[4] = byte(v1 >> 24)
33	dst[5] = byte(v1 >> 16)
34	dst[6] = byte(v1 >> 8)
35	dst[7] = byte(v1 >> 0)
36}
37
38// encryptBlock encrypts a single 8 byte block using XTEA.
39func encryptBlock(c *Cipher, dst, src []byte) {
40	v0, v1 := blockToUint32(src)
41
42	// Two rounds of XTEA applied per loop
43	for i := 0; i < numRounds; {
44		v0 += ((v1<<4 ^ v1>>5) + v1) ^ c.table[i]
45		i++
46		v1 += ((v0<<4 ^ v0>>5) + v0) ^ c.table[i]
47		i++
48	}
49
50	uint32ToBlock(v0, v1, dst)
51}
52
53// decryptBlock decrypts a single 8 byte block using XTEA.
54func decryptBlock(c *Cipher, dst, src []byte) {
55	v0, v1 := blockToUint32(src)
56
57	// Two rounds of XTEA applied per loop
58	for i := numRounds; i > 0; {
59		i--
60		v1 -= ((v0<<4 ^ v0>>5) + v0) ^ c.table[i]
61		i--
62		v0 -= ((v1<<4 ^ v1>>5) + v1) ^ c.table[i]
63	}
64
65	uint32ToBlock(v0, v1, dst)
66}
67