git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/crypto/chacha20/xchacha20.go (about) 1 package chacha20 2 3 import ( 4 "errors" 5 6 "git.sr.ht/~pingoo/stdx/crypto/chacha" 7 ) 8 9 const ( 10 NonceSizeX = 24 11 ) 12 13 var ( 14 ErrBadNonceXLength = errors.New("chacha20: bad nonce length for XChaCha20. 24 bytes required") 15 ) 16 17 // NewX returns a new instance of the XChaCha20 stream cipher. 18 // as of now we use the IETF chacha20 variant with 96-bit nonces 19 func NewX(key, nonce []byte) (StreamCipher, error) { 20 // encryptionKey := make([]byte, 32) 21 // chachaNonce := make([]byte, 12) 22 23 if len(key) != KeySize { 24 return nil, ErrBadKeyLength 25 } 26 if len(nonce) != NonceSizeX { 27 return nil, ErrBadNonceXLength 28 } 29 30 // derive chacha's encryption key from the original key and the first 128 bits of the nonce 31 chachaKey, _ := chacha.HChaCha20(key, nonce[0:16]) 32 // use the last 64 bits of the nonce as the nonce for chacha 33 // copy(chachaNonce[4:12], nonce[16:24]) 34 return New(chachaKey, nonce[16:24]) 35 }