The Go Programming Language

Source file src/pkg/crypto/rc4/rc4.go

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

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.