aboutsummaryrefslogtreecommitdiff
path: root/internal/stupidgcm/chacha.go
blob: 30d57e352beba2006f235ce5df2eaed9dc02e824 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// +build !without_openssl

package stupidgcm

import (
	"crypto/cipher"
	"log"

	"golang.org/x/crypto/chacha20poly1305"
)

/*
#include <openssl/evp.h>
*/
import "C"

type stupidChacha20poly1305 struct {
	stupidAEADCommon
}

// Verify that we satisfy the cipher.AEAD interface
var _ cipher.AEAD = &stupidChacha20poly1305{}

// _EVP_chacha20_poly1305 caches C.EVP_chacha20_poly1305() to avoid the Cgo call
// overhead for each instantiation of NewChacha20poly1305.
var _EVP_chacha20_poly1305 *C.EVP_CIPHER

func init() {
	_EVP_chacha20_poly1305 = C.EVP_chacha20_poly1305()
}

// NewChacha20poly1305 returns a new instance of the OpenSSL ChaCha20-Poly1305 AEAD
// cipher ( https://www.openssl.org/docs/man1.1.1/man3/EVP_chacha20_poly1305.html ).
//
// gocryptfs only uses ChaCha20-Poly1305 as a building block for OpenSSL
// XChaCha20-Poly1305. This function is hot because it gets called once for each
// block by XChaCha20-Poly1305.
func NewChacha20poly1305(key []byte) *stupidChacha20poly1305 {
	if len(key) != chacha20poly1305.KeySize {
		log.Panicf("Only %d-byte keys are supported, you passed %d bytes", chacha20poly1305.KeySize, len(key))
	}
	// private copy
	key2 := make([]byte, chacha20poly1305.KeySize)
	copy(key2, key)
	return &stupidChacha20poly1305{
		stupidAEADCommon{
			key:              key2,
			openSSLEVPCipher: _EVP_chacha20_poly1305,
			nonceSize:        chacha20poly1305.NonceSize,
		},
	}
}