aboutsummaryrefslogtreecommitdiff
path: root/cryptfs/cryptfs.go
blob: 71ec996f9d5c8e4ef5d1ad227f69d5336323b049 (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
63
package cryptfs

// CryptFS is the crypto backend of GoCryptFS

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

const (
	KEY_LEN = 16
	NONCE_LEN = 12
	AUTH_TAG_LEN = 16
	DEFAULT_PLAINBS = 4096
)

type CryptFS struct {
	blockCipher cipher.Block
	gcm cipher.AEAD
	plainBS	uint64
	cipherBS uint64
	// Stores an all-zero block of size cipherBS
	allZeroBlock []byte
}

func NewCryptFS(key []byte, useOpenssl bool) *CryptFS {

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

	b, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}

	var gcm cipher.AEAD
	if useOpenssl {
		var k16 [16]byte
		copy(k16[:], key)
		gcm = opensslGCM{k16}
	} else {
		gcm, err = cipher.NewGCM(b)
		if err != nil {
			panic(err)
		}
	}

	cipherBS := DEFAULT_PLAINBS + NONCE_LEN + AUTH_TAG_LEN

	return &CryptFS{
		blockCipher: b,
		gcm: gcm,
		plainBS: DEFAULT_PLAINBS,
		cipherBS: uint64(cipherBS),
		allZeroBlock: make([]byte, cipherBS),
	}
}

func (be *CryptFS) PlainBS() uint64 {
	return be.plainBS
}