123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- package chacha20poly1305
- import (
- "crypto/cipher"
- "encoding/binary"
- "errors"
- )
- const (
-
- KeySize = 32
-
-
-
-
-
- NonceSize = 12
-
-
- NonceSizeX = 24
- )
- type chacha20poly1305 struct {
- key [8]uint32
- }
- func New(key []byte) (cipher.AEAD, error) {
- if len(key) != KeySize {
- return nil, errors.New("chacha20poly1305: bad key length")
- }
- ret := new(chacha20poly1305)
- ret.key[0] = binary.LittleEndian.Uint32(key[0:4])
- ret.key[1] = binary.LittleEndian.Uint32(key[4:8])
- ret.key[2] = binary.LittleEndian.Uint32(key[8:12])
- ret.key[3] = binary.LittleEndian.Uint32(key[12:16])
- ret.key[4] = binary.LittleEndian.Uint32(key[16:20])
- ret.key[5] = binary.LittleEndian.Uint32(key[20:24])
- ret.key[6] = binary.LittleEndian.Uint32(key[24:28])
- ret.key[7] = binary.LittleEndian.Uint32(key[28:32])
- return ret, nil
- }
- func (c *chacha20poly1305) NonceSize() int {
- return NonceSize
- }
- func (c *chacha20poly1305) Overhead() int {
- return 16
- }
- func (c *chacha20poly1305) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
- if len(nonce) != NonceSize {
- panic("chacha20poly1305: bad nonce length passed to Seal")
- }
- if uint64(len(plaintext)) > (1<<38)-64 {
- panic("chacha20poly1305: plaintext too large")
- }
- return c.seal(dst, nonce, plaintext, additionalData)
- }
- var errOpen = errors.New("chacha20poly1305: message authentication failed")
- func (c *chacha20poly1305) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
- if len(nonce) != NonceSize {
- panic("chacha20poly1305: bad nonce length passed to Open")
- }
- if len(ciphertext) < 16 {
- return nil, errOpen
- }
- if uint64(len(ciphertext)) > (1<<38)-48 {
- panic("chacha20poly1305: ciphertext too large")
- }
- return c.open(dst, nonce, ciphertext, additionalData)
- }
- func sliceForAppend(in []byte, n int) (head, tail []byte) {
- if total := len(in) + n; cap(in) >= total {
- head = in[:total]
- } else {
- head = make([]byte, total)
- copy(head, in)
- }
- tail = head[len(in):]
- return
- }
|