libgocryptfs/cryptfs/cryptfs.go

82 lines
1.6 KiB
Go
Raw Normal View History

2015-09-03 18:57:28 +02:00
package cryptfs
2015-09-03 18:22:18 +02:00
2015-09-05 20:30:20 +02:00
// CryptFS is the crypto backend of GoCryptFS
2015-09-03 18:22:18 +02:00
import (
2015-09-03 18:57:28 +02:00
"crypto/aes"
2015-10-04 14:36:20 +02:00
"crypto/cipher"
"fmt"
2015-09-03 18:22:18 +02:00
)
2015-09-03 18:57:28 +02:00
const (
DEFAULT_PLAINBS = 4096
KEY_LEN = 32 // AES-256
2015-10-04 14:36:20 +02:00
AUTH_TAG_LEN = 16
DIRIV_LEN = 16 // identical to AES block size
DIRIV_FILENAME = "gocryptfs.diriv"
2015-09-03 18:57:28 +02:00
)
type CryptFS struct {
2015-09-03 18:57:28 +02:00
blockCipher cipher.Block
2015-10-04 14:36:20 +02:00
gcm cipher.AEAD
gcmIVLen int
gcmIVGen nonceGenerator
2015-10-04 14:36:20 +02:00
plainBS uint64
cipherBS uint64
// Stores an all-zero block of size cipherBS
2015-12-13 20:10:52 +01:00
allZeroBlock []byte
// DirIV cache for filename encryption
DirIVCacheEnc DirIVCache
2015-09-03 18:57:28 +02:00
}
func NewCryptFS(key []byte, useOpenssl bool, plaintextNames bool, GCMIV128 bool) *CryptFS {
2015-09-03 18:57:28 +02:00
if len(key) != KEY_LEN {
panic(fmt.Sprintf("Unsupported key length %d", len(key)))
}
b, err := aes.NewCipher(key)
2015-09-03 18:57:28 +02:00
if err != nil {
panic(err)
}
// We want the IV size in bytes
gcmIV := 96 / 8
if GCMIV128 {
gcmIV = 128 / 8
}
var gcm cipher.AEAD
if useOpenssl {
gcm = opensslGCM{key}
} else {
gcm, err = cipher.NewGCMWithNonceSize(b, gcmIV)
if err != nil {
panic(err)
}
2015-09-03 18:57:28 +02:00
}
plainBS := DEFAULT_PLAINBS
cipherBS := plainBS + gcmIV + AUTH_TAG_LEN
return &CryptFS{
2015-12-13 20:10:52 +01:00
blockCipher: b,
gcm: gcm,
gcmIVLen: gcmIV,
gcmIVGen: nonceGenerator{nonceLen: gcmIV},
plainBS: uint64(plainBS),
2015-12-13 20:10:52 +01:00
cipherBS: uint64(cipherBS),
allZeroBlock: make([]byte, cipherBS),
2015-09-03 18:57:28 +02:00
}
}
// Get plaintext block size
2015-09-05 20:11:20 +02:00
func (be *CryptFS) PlainBS() uint64 {
2015-09-05 19:07:20 +02:00
return be.plainBS
}
// Per-block storage overhead
func (be *CryptFS) BlockOverhead() uint64 {
return be.cipherBS - be.plainBS
}