...
Run Format

Source file src/crypto/rc4/rc4.go

Documentation: crypto/rc4

     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  //
     8  // RC4 is cryptographically broken and should not be used for secure
     9  // applications.
    10  package rc4
    11  
    12  import "strconv"
    13  
    14  // A Cipher is an instance of RC4 using a particular key.
    15  type Cipher struct {
    16  	s    [256]uint32
    17  	i, j uint8
    18  }
    19  
    20  type KeySizeError int
    21  
    22  func (k KeySizeError) Error() string {
    23  	return "crypto/rc4: invalid key size " + strconv.Itoa(int(k))
    24  }
    25  
    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) {
    29  	k := len(key)
    30  	if k < 1 || k > 256 {
    31  		return nil, KeySizeError(k)
    32  	}
    33  	var c Cipher
    34  	for i := 0; i < 256; i++ {
    35  		c.s[i] = uint32(i)
    36  	}
    37  	var j uint8 = 0
    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]
    41  	}
    42  	return &c, nil
    43  }
    44  
    45  // Reset zeros the key data so that it will no longer appear in the
    46  // process's memory.
    47  func (c *Cipher) Reset() {
    48  	for i := range c.s {
    49  		c.s[i] = 0
    50  	}
    51  	c.i, c.j = 0, 0
    52  }
    53  
    54  // xorKeyStreamGeneric sets dst to the result of XORing src with the
    55  // key stream. Dst and src must overlap entirely or not at all.
    56  //
    57  // This is the pure Go version. rc4_{amd64,386,arm}* contain assembly
    58  // implementations. This is here for tests and to prevent bitrot.
    59  func (c *Cipher) xorKeyStreamGeneric(dst, src []byte) {
    60  	i, j := c.i, c.j
    61  	for k, v := range src {
    62  		i += 1
    63  		j += uint8(c.s[i])
    64  		c.s[i], c.s[j] = c.s[j], c.s[i]
    65  		dst[k] = v ^ uint8(c.s[uint8(c.s[i]+c.s[j])])
    66  	}
    67  	c.i, c.j = i, j
    68  }
    69  

View as plain text