summaryrefslogtreecommitdiff
path: root/cryptfs/names_diriv.go
blob: c9debab84a40fc9ac7e4ccbcd97fa8c819480315 (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
64
65
66
67
68
69
package cryptfs

import (
	"path/filepath"
	"io/ioutil"
	"fmt"
	"strings"
)

// readDirIV - read the "gocryptfs.diriv" file from "dir" (absolute path)
func (be *CryptFS) readDirIV(dir string) (iv []byte, err error) {
		ivfile := filepath.Join(dir, DIRIV_FILENAME)
		iv, err = ioutil.ReadFile(ivfile)
		if err != nil {
			Warn.Printf("readDirIV: %v\n", err)
			return nil, err
		}
		if len(iv) != DIRIV_LEN {
			return nil, fmt.Errorf("readDirIV: Invalid length %d\n", len(iv))
		}
		return iv, nil
}

// EncryptPathDirIV - encrypt path using CBC with DirIV
func (be *CryptFS) EncryptPathDirIV(plainPath string, rootDir string) (string, error) {
	if be.plaintextNames {
		return plainPath, nil
	}
	// Empty string means root directory
	if plainPath == "" {
		return plainPath, nil
	}
	var wd = rootDir
	var encryptedNames []string
	plainNames := strings.Split(plainPath, "/")
	for _, plainName := range plainNames {
		iv, err := be.readDirIV(wd)
		if err != nil {
			return "", err
		}
		encryptedName := be.encryptName(plainName, iv)
		encryptedNames = append(encryptedNames, encryptedName)
		wd = filepath.Join(wd, encryptedName)
	}
	return filepath.Join(encryptedNames...), nil
}

// DecryptPathDirIV - encrypt path using CBC with DirIV
func (be *CryptFS) DecryptPathDirIV(encryptedPath string, rootDir string) (string, error) {
	if be.plaintextNames {
		return encryptedPath, nil
	}
	var wd = rootDir
	var plainNames []string
	encryptedNames := strings.Split(encryptedPath, "/")
	for _, encryptedName := range encryptedNames {
		iv, err := be.readDirIV(wd)
		if err != nil {
			return "", err
		}
		plainName, err := be.decryptName(encryptedName, iv)
		if err != nil {
			return "", err
		}
		plainNames = append(plainNames, plainName)
		wd = filepath.Join(wd, encryptedName)
	}
	return filepath.Join(plainNames...), nil
}