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 rc4 implements RC4 encryption, as defined in Bruce Schneier's
6 // Applied Cryptography.
9 // BUG(agl): RC4 is in common use but has design weaknesses that make
10 // it a poor choice for new protocols.
14 // A Cipher is an instance of RC4 using a particular key.
22 func (k KeySizeError
) Error() string {
23 return "crypto/rc4: invalid key size " + strconv
.Itoa(int(k
))
26 // NewCipher creates and returns a new Cipher. The key argument should be the
27 // RC4 key, at least 1 byte and at most 256 bytes.
28 func NewCipher(key
[]byte) (*Cipher
, error
) {
31 return nil, KeySizeError(k
)
34 for i
:= 0; i
< 256; i
++ {
38 for i
:= 0; i
< 256; i
++ {
39 j
+= uint8(c
.s
[i
]) + key
[i%k
]
40 c
.s
[i
], c
.s
[j
] = c
.s
[j
], c
.s
[i
]
45 // Reset zeros the key data so that it will no longer appear in the
47 func (c
*Cipher
) Reset() {
54 // xorKeyStreamGeneric sets dst to the result of XORing src with the
55 // key stream. Dst and src may be the same slice but otherwise should
58 // This is the pure Go version. rc4_{amd64,386,arm}* contain assembly
59 // implementations. This is here for tests and to prevent bitrot.
60 func (c
*Cipher
) xorKeyStreamGeneric(dst
, src
[]byte) {
62 for k
, v
:= range src
{
65 c
.s
[i
], c
.s
[j
] = c
.s
[j
], c
.s
[i
]
66 dst
[k
] = v
^ uint8(c
.s
[uint8(c
.s
[i
]+c
.s
[j
])])