cipher.go 2.4 KB

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