golang rc4 结果不正确.
package main import ( "crypto/rc4" "fmt" ) func main() { rc, err := rc4.NewCipher([]byte("5813aecc-0d05-497e-aafa-3111610cf44c")) if err != nil { panic(err) } src := []byte("hello world") fmt.Println(src) rc.XORKeyStream(src, src) fmt.Println(src) rc.XORKeyStream(src, src) fmt.Println(src) }
输出:
[104 101 108 108 111 32 119 111 114 108 100] [216 36 143 56 20 50 169 207 31 252 154] [0 32 70 107 105 65 236 28 246 248 21]
看了下NewCipher:
// NewCipher creates and returns a new Cipher. The key argument should be the // RC4 key, at least 1 byte and at most 256 bytes. func NewCipher(key []byte) (*Cipher, error) { k := len(key) if k < 1 || k > 256 { return nil, KeySizeError(k) } var c Cipher for i := 0; i < 256; i++ { c.s[i] = uint8(i) } var j uint8 = 0 for i := 0; i < 256; i++ { j += c.s[i] + key[i%k] c.s[i], c.s[j] = c.s[j], c.s[i] } return &c, nil }
XORKeyStream:
// XORKeyStream sets dst to the result of XORing src with the key stream. // Dst and src may be the same slice but otherwise should not overlap. func (c *Cipher) XORKeyStream(dst, src []byte) { for i := range src { c.i += 1 c.j += c.s[c.i] c.s[c.i], c.s[c.j] = c.s[c.j], c.s[c.i] dst[i] = src[i] ^ c.s[c.s[c.i]+c.s[c.j]] } }
这里并不是简单的异或运算,所以执行两次以后不会有xor运算的性质
每次XORKeyStream之前都要执行一下
rc4.NewCipher([]byte("5813aecc-0d05-497e-aafa-3111610cf44c"))