rc4.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 rc4 implements RC4 encryption, as defined in Bruce Schneier's
  5. // Applied Cryptography.
  6. package rc4
  7. // BUG(agl): RC4 is in common use but has design weaknesses that make
  8. // it a poor choice for new protocols.
  9. import "strconv"
  10. // A Cipher is an instance of RC4 using a particular key.
  11. type Cipher struct {
  12. s [256]uint32
  13. i, j uint8
  14. }
  15. type KeySizeError int
  16. func (k KeySizeError) Error() string {
  17. return "crypto/rc4: invalid key size " + strconv.Itoa(int(k))
  18. }
  19. // NewCipher creates and returns a new Cipher. The key argument should be the
  20. // RC4 key, at least 1 byte and at most 256 bytes.
  21. func NewCipher(key []byte) (*Cipher, error) {
  22. k := len(key)
  23. if k < 1 || k > 256 {
  24. return nil, KeySizeError(k)
  25. }
  26. var c Cipher
  27. for i := 0; i < 256; i++ {
  28. c.s[i] = uint32(i)
  29. }
  30. var j uint8 = 0
  31. for i := 0; i < 256; i++ {
  32. j += uint8(c.s[i]) + key[i%k]
  33. c.s[i], c.s[j] = c.s[j], c.s[i]
  34. }
  35. return &c, nil
  36. }
  37. // Reset zeros the key data so that it will no longer appear in the
  38. // process's memory.
  39. func (c *Cipher) Reset() {
  40. for i := range c.s {
  41. c.s[i] = 0
  42. }
  43. c.i, c.j = 0, 0
  44. }
  45. // xorKeyStreamGeneric sets dst to the result of XORing src with the
  46. // key stream. Dst and src may be the same slice but otherwise should
  47. // not overlap.
  48. //
  49. // This is the pure Go version. rc4_{amd64,386,arm}* contain assembly
  50. // implementations. This is here for tests and to prevent bitrot.
  51. func (c *Cipher) xorKeyStreamGeneric(dst, src []byte) {
  52. i, j := c.i, c.j
  53. for k, v := range src {
  54. i += 1
  55. j += uint8(c.s[i])
  56. c.s[i], c.s[j] = c.s[j], c.s[i]
  57. dst[k] = v ^ uint8(c.s[uint8(c.s[i]+c.s[j])])
  58. }
  59. c.i, c.j = i, j
  60. }