1 // Copyright 2015 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.
5 // Package tea implements the TEA algorithm, as defined in Needham and
6 // Wheeler's 1994 technical report, “TEA, a Tiny Encryption Algorithm”. See
7 // http://www.cix.co.uk/~klockstone/tea.pdf for details.
17 // BlockSize is the size of a TEA block, in bytes.
20 // KeySize is the size of a TEA key, in bytes.
23 // delta is the TEA key schedule constant.
26 // numRounds is the standard number of rounds in TEA.
30 // tea is an instance of the TEA cipher with a particular key.
36 // NewCipher returns an instance of the TEA cipher with the standard number of
37 // rounds. The key argument must be 16 bytes long.
38 func NewCipher(key []byte) (cipher.Block, error) {
39 return NewCipherWithRounds(key, numRounds)
42 // NewCipherWithRounds returns an instance of the TEA cipher with a given
43 // number of rounds, which must be even. The key argument must be 16 bytes
45 func NewCipherWithRounds(key []byte, rounds int) (cipher.Block, error) {
47 return nil, errors.New("tea: incorrect key size")
51 return nil, errors.New("tea: odd number of rounds specified")
62 // BlockSize returns the TEA block size, which is eight bytes. It is necessary
63 // to satisfy the Block interface in the package "crypto/cipher".
64 func (*tea) BlockSize() int {
68 // Encrypt encrypts the 8 byte buffer src using the key in t and stores the
69 // result in dst. Note that for amounts of data larger than a block, it is not
70 // safe to just call Encrypt on successive blocks; instead, use an encryption
71 // mode like CBC (see crypto/cipher/cbc.go).
72 func (t *tea) Encrypt(dst, src []byte) {
74 v0, v1 := e.Uint32(src), e.Uint32(src[4:])
75 k0, k1, k2, k3 := e.Uint32(t.key[0:]), e.Uint32(t.key[4:]), e.Uint32(t.key[8:]), e.Uint32(t.key[12:])
78 delta := uint32(delta)
80 for i := 0; i < t.rounds/2; i++ {
82 v0 += ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1)
83 v1 += ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3)
87 e.PutUint32(dst[4:], v1)
90 // Decrypt decrypts the 8 byte buffer src using the key in t and stores the
92 func (t *tea) Decrypt(dst, src []byte) {
94 v0, v1 := e.Uint32(src), e.Uint32(src[4:])
95 k0, k1, k2, k3 := e.Uint32(t.key[0:]), e.Uint32(t.key[4:]), e.Uint32(t.key[8:]), e.Uint32(t.key[12:])
97 delta := uint32(delta)
98 sum := delta * uint32(t.rounds/2) // in general, sum = delta * n
100 for i := 0; i < t.rounds/2; i++ {
101 v1 -= ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3)
102 v0 -= ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1)
107 e.PutUint32(dst[4:], v1)