summaryrefslogtreecommitdiff
path: root/internal/cryptocore/cryptocore.go
blob: a9731be108a414e57d6fe21992a5e8d92eb28cd8 (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
53
54
55
56
57
58
59
60
61
62
// Package cryptocore wraps OpenSSL and Go GCM crypto and provides
// a nonce generator.
package cryptocore

import (
	"crypto/aes"
	"crypto/cipher"
	"fmt"

	"github.com/rfjakob/gocryptfs/internal/stupidgcm"
)

const (
	KeyLen     = 32 // AES-256
	AuthTagLen = 16
)

type CryptoCore struct {
	BlockCipher cipher.Block
	Gcm         cipher.AEAD
	GcmIVGen    *nonceGenerator
	IVLen       int
}

// "New" returns a new CryptoCore object or panics.
func New(key []byte, useOpenssl bool, GCMIV128 bool) *CryptoCore {

	if len(key) != KeyLen {
		panic(fmt.Sprintf("Unsupported key length %d", len(key)))
	}

	// We want the IV size in bytes
	IVLen := 96 / 8
	if GCMIV128 {
		IVLen = 128 / 8
	}

	// We always use built-in Go crypto for blockCipher because it is not
	// performance-critical.
	blockCipher, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}

	var gcm cipher.AEAD
	if useOpenssl && GCMIV128 {
		// stupidgcm only supports 128-bit IVs
		gcm = stupidgcm.New(key)
	} else {
		gcm, err = goGCMWrapper(blockCipher, IVLen)
		if err != nil {
			panic(err)
		}
	}

	return &CryptoCore{
		BlockCipher: blockCipher,
		Gcm:         gcm,
		GcmIVGen:    &nonceGenerator{nonceLen: IVLen},
		IVLen:       IVLen,
	}
}