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.
5 // Package xtea implements XTEA encryption, as defined in Needham and Wheeler's
6 // 1997 technical report, "Tea extensions."
7 package xtea // import "golang.org/x/crypto/xtea"
9 // For details, see http://www.cix.co.uk/~klockstone/xtea.pdf
13 // The XTEA block size in bytes.
16 // A Cipher is an instance of an XTEA cipher using a particular key.
17 // table contains a series of precalculated values that are used each round.
24 func (k KeySizeError) Error() string {
25 return "crypto/xtea: invalid key size " + strconv.Itoa(int(k))
28 // NewCipher creates and returns a new Cipher.
29 // The key argument should be the XTEA key.
30 // XTEA only supports 128 bit (16 byte) keys.
31 func NewCipher(key []byte) (*Cipher, error) {
35 return nil, KeySizeError(k)
46 // BlockSize returns the XTEA block size, 8 bytes.
47 // It is necessary to satisfy the Block interface in the
48 // package "crypto/cipher".
49 func (c *Cipher) BlockSize() int { return BlockSize }
51 // Encrypt encrypts the 8 byte buffer src using the key and stores the result in dst.
52 // Note that for amounts of data larger than a block,
53 // it is not safe to just call Encrypt on successive blocks;
54 // instead, use an encryption mode like CBC (see crypto/cipher/cbc.go).
55 func (c *Cipher) Encrypt(dst, src []byte) { encryptBlock(c, dst, src) }
57 // Decrypt decrypts the 8 byte buffer src using the key k and stores the result in dst.
58 func (c *Cipher) Decrypt(dst, src []byte) { decryptBlock(c, dst, src) }
60 // initCipher initializes the cipher context by creating a look up table
61 // of precalculated values that are based on the key.
62 func initCipher(c *Cipher, key []byte) {
63 // Load the key into four uint32s
65 for i := 0; i < len(k); i++ {
66 j := i << 2 // Multiply by 4
67 k[i] = uint32(key[j+0])<<24 | uint32(key[j+1])<<16 | uint32(key[j+2])<<8 | uint32(key[j+3])
70 // Precalculate the table
71 const delta = 0x9E3779B9
74 // Two rounds of XTEA applied per loop
75 for i := 0; i < numRounds; {
76 c.table[i] = sum + k[sum&3]
79 c.table[i] = sum + k[(sum>>11)&3]