tea.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package util
  2. import (
  3. "encoding/binary"
  4. "strconv"
  5. )
  6. type teaCipher struct {
  7. key []byte
  8. }
  9. type KeySizeError int
  10. func (k KeySizeError) Error() string {
  11. return "tea: invalid key size " + strconv.Itoa(int(k))
  12. }
  13. func NewCipher(key []byte) (*teaCipher, error) {
  14. if len(key) != 16 {
  15. return nil, KeySizeError(len(key))
  16. }
  17. cipher := new(teaCipher)
  18. cipher.key = key
  19. return cipher, nil
  20. }
  21. func (c *teaCipher) BlockSize() int {
  22. return 8
  23. }
  24. func (c *teaCipher) Encrypt(dst, src []byte) {
  25. var (
  26. end = binary.BigEndian
  27. v0, v1 uint32 = end.Uint32(src), end.Uint32(src[4:])
  28. sum uint32 = 0
  29. delta uint32 = 0x9E3779B9
  30. k0, k1, k2, k3 uint32 = end.Uint32(c.key[0:]),
  31. end.Uint32(c.key[4:]),
  32. end.Uint32(c.key[8:]),
  33. end.Uint32(c.key[12:])
  34. )
  35. for i := 0; i < 32; i++ {
  36. sum += delta
  37. v0 += ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1)
  38. v1 += ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3)
  39. }
  40. end.PutUint32(dst, v0)
  41. end.PutUint32(dst[4:], v1)
  42. }
  43. func (c *teaCipher) Decrypt(dst, src []byte) {
  44. var (
  45. end = binary.BigEndian
  46. v0, v1 uint32 = end.Uint32(src[0:4]), end.Uint32(src[4:8])
  47. delta uint32 = 0x9E3779B9
  48. sum uint32 = delta << 5
  49. k0, k1, k2, k3 uint32 = end.Uint32(c.key[0:]),
  50. end.Uint32(c.key[4:]),
  51. end.Uint32(c.key[8:]),
  52. end.Uint32(c.key[12:])
  53. )
  54. for i := 0; i < 32; i++ {
  55. v1 -= ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3)
  56. v0 -= ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1)
  57. sum -= delta
  58. }
  59. end.PutUint32(dst, v0)
  60. end.PutUint32(dst[4:], v1)
  61. }
  62. func (c *teaCipher) Clear() {
  63. for i := 0; i < len(c.key); i++ {
  64. c.key[i] = 0
  65. }
  66. }