From e304e2761d30a6d87357b1cbca58ae0629c44cf2 Mon Sep 17 00:00:00 2001 From: v2ray Date: Sat, 23 Jul 2016 13:04:44 +0200 Subject: [PATCH] refine chacha20 initialization --- common/crypto/chacha20.go | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/common/crypto/chacha20.go b/common/crypto/chacha20.go index eed0243e..0c9aabfc 100644 --- a/common/crypto/chacha20.go +++ b/common/crypto/chacha20.go @@ -6,24 +6,16 @@ import ( "github.com/aead/chacha20" ) -func makeNonce(nonce *[chacha20.NonceSize]byte, iv []byte) { +// NewChaCha20Stream creates a new Chacha/20 cipher stream. Caller must ensure that key is 32-bytes long and iv is either 8 or 12 bytes. +func NewChaCha20Stream(key []byte, iv []byte) cipher.Stream { + var keyArray [32]byte + var nonce [12]byte + copy(keyArray[:], key) switch len(iv) { case 8: copy(nonce[4:], iv) case 12: copy(nonce[:], iv) - default: - panic("bad nonce length") - } -} - -func NewChaCha20Stream(key []byte, iv []byte) cipher.Stream { - var Key [32]byte - var Nonce [12]byte - if len(key) != 32 { - panic("bad key length") } - copy(Key[:], key) - makeNonce(&Nonce, iv) - return chacha20.NewCipher(&Nonce, &Key) + return chacha20.NewCipher(&nonce, &keyArray) }