github.com/studentmain/smaead@v0.0.0-20210101171653-e876413b9e86/partial_c20p1305.go (about) 1 // Copyright 2016 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 package smaead 5 6 import ( 7 "errors" 8 "golang.org/x/crypto/chacha20" 9 ) 10 11 const ( 12 // KeySize is the size of the key used by this AEAD, in bytes. 13 KeySize = 32 14 15 // NonceSize is the size of the nonce used with the standard variant of this 16 // AEAD, in bytes. 17 // 18 // Note that this is too short to be safely generated at random if the same 19 // key is reused more than 2³² times. 20 NonceSize = 12 21 22 // NonceSizeX is the size of the nonce used with the XChaCha20-Poly1305 23 // variant of this AEAD, in bytes. 24 NonceSizeX = 24 25 ) 26 27 type Chacha20poly1305 struct { 28 key [KeySize]byte 29 } 30 31 // New returns a ChaCha20-Poly1305 AEAD that uses the given 256-bit key. 32 func NewPartialChacha20Poly1305(key []byte) (*Chacha20poly1305, error) { 33 if len(key) != KeySize { 34 return nil, errors.New("smaead.c20p1305: bad key length") 35 } 36 ret := new(Chacha20poly1305) 37 copy(ret.key[:], key) 38 return ret, nil 39 } 40 41 func (c *Chacha20poly1305) OpenWithoutCheck(dst, nonce, ciphertext []byte) []byte { 42 s, _ := chacha20.NewUnauthenticatedCipher(c.key[:], nonce) 43 s.SetCounter(1) // set the counter to 1, skipping 32 bytes 44 45 ret, out := sliceForAppend(dst, len(ciphertext)) 46 if inexactOverlap(out, ciphertext) { 47 panic("smaead.c20p1305: invalid buffer overlap") 48 } 49 50 s.XORKeyStream(out, ciphertext) 51 return ret 52 }