Skip to content

Commit 26e6154

Browse files
chore: remove user input password for encryption
1 parent ada9558 commit 26e6154

File tree

2 files changed

+40
-161
lines changed

2 files changed

+40
-161
lines changed

system/backup/encrypt.go

Lines changed: 20 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -4,57 +4,41 @@ import (
44
"crypto/aes"
55
"crypto/cipher"
66
"crypto/rand"
7-
"crypto/sha256"
87
"encoding/base64"
98
"fmt"
109
"io"
1110
"os"
1211
)
1312

14-
// encryption formatt
13+
//simplified encryption config without password
1514
type EncryptionConfig struct {
16-
17-
Password string
18-
Salt []byte
15+
Key []byte // Direct 32-byte key instead of password+salt
1916
}
2017

21-
// AES-GCM encrpption with password based derivation
18+
//AES-GCM encryption with direct key (no password derivation)
2219
func EncryptFile(filePath string, config *EncryptionConfig) (string, error) {
23-
2420
data, err := os.ReadFile(filePath)
25-
26-
if err != nil {
27-
28-
return "", fmt.Errorf("failed to read file %s: %w", filePath, err)
29-
30-
}
31-
32-
// derive key from password+salt
33-
key := deriveKey(config.Password, config.Salt)
21+
if err != nil {
22+
return "", fmt.Errorf("failed to read file %s: %w", filePath, err)
23+
}
3424

35-
// AES cipher from key
36-
block, err := aes.NewCipher(key)
25+
//use direct key (no password derivation)
26+
block, err := aes.NewCipher(config.Key)
3727
if err != nil {
38-
39-
return "", fmt.Errorf("failed to create cipher: %w", err)
40-
41-
}
28+
return "", fmt.Errorf("failed to create cipher: %w", err)
29+
}
4230

4331
// GCM mode from AES block
4432
gcm, err := cipher.NewGCM(block)
4533
if err != nil {
46-
47-
return "", fmt.Errorf("failed to create GCM: %w", err)
48-
49-
}
34+
return "", fmt.Errorf("failed to create GCM: %w", err)
35+
}
5036

51-
//generate nonce
37+
// Generate nonce
5238
nonce := make([]byte, gcm.NonceSize())
5339
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
54-
55-
return "", fmt.Errorf("failed to generate nonce: %w", err)
56-
57-
}
40+
return "", fmt.Errorf("failed to generate nonce: %w", err)
41+
}
5842

5943
//encrypt data with nonce
6044
ciphertext := gcm.Seal(nonce, nonce, data, nil)
@@ -64,69 +48,9 @@ func EncryptFile(filePath string, config *EncryptionConfig) (string, error) {
6448
return encoded, nil
6549
}
6650

67-
// // decryption methods - will be used later
68-
// func DecryptFile(encryptedData string, config *EncryptionConfig) ([]byte, error) {
69-
// ///decode from base64
70-
// ciphertext, err := base64.StdEncoding.DecodeString(encryptedData)
71-
// if err != nil {
72-
73-
// return nil, fmt.Errorf("failed to decode base64: %w", err)
74-
75-
// }
76-
77-
// //derive key from password
78-
// key := deriveKey(config.Password, config.Salt)
79-
80-
// //create AES cipher
81-
// block, err := aes.NewCipher(key)
82-
// if err != nil {
83-
84-
// return nil, fmt.Errorf("failed to create cipher: %w", err)
85-
86-
// }
87-
88-
// //create GCM mode
89-
// gcm, err := cipher.NewGCM(block)
90-
// if err != nil {
91-
92-
// return nil, fmt.Errorf("failed to create GCM: %w", err)
93-
94-
// }
95-
96-
// //extract nonce
97-
// nonceSize := gcm.NonceSize()
98-
// if len(ciphertext) < nonceSize {
99-
100-
// return nil, fmt.Errorf("ciphertext too short")
101-
102-
// }
103-
104-
// nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
105-
106-
// //decrypt data
107-
// plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
108-
// if err != nil {
109-
110-
// return nil, fmt.Errorf("failed to decrypt: %w", err)
111-
112-
// }
113-
114-
// return plaintext, nil
115-
// }
116-
117-
118-
119-
// derive a 32-byte key from password and salt using SHA-256
120-
func deriveKey(password string, salt []byte) []byte {
121-
hash := sha256.New()
122-
hash.Write([]byte(password))
123-
hash.Write(salt)
124-
return hash.Sum(nil)
125-
}
126-
127-
//create a random salt for key derivation
128-
func GenerateSalt() ([]byte, error) {
129-
salt := make([]byte, 32)
130-
_, err := rand.Read(salt)
131-
return salt, err
51+
//generate a random 32-byte key for AES-256
52+
func GenerateKey() ([]byte, error) {
53+
key := make([]byte, 32) // 32 bytes for AES-256
54+
_, err := rand.Read(key)
55+
return key, err
13256
}

system/backup/key.go

Lines changed: 20 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -9,25 +9,22 @@ import (
99
"os"
1010
"path/filepath"
1111
"strings"
12-
"syscall"
1312
"time"
14-
15-
"golang.org/x/term"
1613
)
1714

18-
//structure of backed up keys
15+
// Structure of backed up keys (removed Salt field)
1916
type BackupData struct {
2017

2118
Timestamp time.Time `json:"timestamp"`
2219

23-
SystemInfo SystemInfo `json:"system_info"`
20+
SystemInfo SystemInfo `json:"system_info"`
2421

25-
EncryptedKeys map[string]EncryptedKey `json:"encrypted_keys"`
22+
EncryptedKeys map[string]EncryptedKey `json:"encrypted_keys"`
2623

27-
Salt []byte `json:"salt"`
24+
EncryptionKey []byte `json:"encryption_key"` // Store the key directly
2825
}
2926

30-
// basic system information
27+
// Basic system information
3128
type SystemInfo struct {
3229

3330
Hostname string `json:"hostname"`
@@ -53,29 +50,23 @@ type EncryptedKey struct {
5350
type BackupManager struct {
5451
config *EncryptionConfig
5552
}
53+
5654
func NewBackupManager() *BackupManager {
5755
return &BackupManager{}
5856
}
5957

60-
// create a complete backup of keys
58+
//create a complete backup of keys (no password required)
6159
func (bm *BackupManager) CreateBackup(customPaths []string) error {
6260
fmt.Println("Starting key backup process...")
6361

64-
//password for encryption
65-
password, err := bm.getPassword()
66-
if err != nil {
67-
return fmt.Errorf("failed to get password: %w", err)
68-
}
69-
70-
// generate salt
71-
salt, err := GenerateSalt()
62+
//generate random encryption key (no password needed)
63+
key, err := GenerateKey()
7264
if err != nil {
73-
return fmt.Errorf("failed to generate salt: %w", err)
65+
return fmt.Errorf("failed to generate encryption key: %w", err)
7466
}
7567

7668
bm.config = &EncryptionConfig{
77-
Password: password,
78-
Salt: salt,
69+
Key: key,
7970
}
8071

8172
// search standard locations
@@ -90,7 +81,6 @@ func (bm *BackupManager) CreateBackup(customPaths []string) error {
9081

9182
//combine all locations
9283
allLocations := append(standardLocations, customLocations...)
93-
9484
if len(allLocations) == 0 {
9585
fmt.Println("No key locations found to backup.")
9686
return nil
@@ -101,7 +91,7 @@ func (bm *BackupManager) CreateBackup(customPaths []string) error {
10191
Timestamp: time.Now(),
10292
SystemInfo: bm.getSystemInfo(),
10393
EncryptedKeys: make(map[string]EncryptedKey),
104-
Salt: salt,
94+
EncryptionKey: key, // Store the key in backup data
10595
}
10696

10797
//encrypt and store keys
@@ -116,17 +106,15 @@ func (bm *BackupManager) CreateBackup(customPaths []string) error {
116106

117107
//creating tarball for the backup storing
118108
fmt.Println("Creating backup tarball...")
119-
tarballPath := fmt.Sprintf("dist/key-backup-%s.tar.gz",
109+
tarballPath := fmt.Sprintf("dist/key-backup-%s.tar.gz",
120110
time.Now().Format("2006-01-02-15-04-05"))
121-
122111
err = bm.createTarball(backupData, tarballPath)
123112
if err != nil {
124113
return fmt.Errorf("failed to create tarball: %w", err)
125114
}
126115

127116
fmt.Printf("Backup completed successfully: %s\n", tarballPath)
128117
fmt.Printf("Backed up %d key files\n", len(backupData.EncryptedKeys))
129-
130118
return nil
131119
}
132120

@@ -136,18 +124,14 @@ func (bm *BackupManager) processLocation(location KeyLocation, backupData *Backu
136124
//get file info for permissions
137125
fileInfo, err := os.Stat(filePath)
138126
if err != nil {
139-
140-
continue
141-
142-
}
127+
continue
128+
}
143129

144130
// call encryption of the file
145131
encryptedData, err := EncryptFile(filePath, bm.config)
146132
if err != nil {
147-
148-
return fmt.Errorf("failed to encrypt %s: %w", filePath, err)
149-
150-
}
133+
return fmt.Errorf("failed to encrypt %s: %w", filePath, err)
134+
}
151135

152136
// store encrypted key
153137
keyID := filepath.Base(filePath) + "_" + strings.ReplaceAll(filePath, "/", "_")
@@ -164,13 +148,10 @@ func (bm *BackupManager) processLocation(location KeyLocation, backupData *Backu
164148
// processCustomPaths converts custom paths to KeyLocation objects
165149
func (bm *BackupManager) processCustomPaths(customPaths []string) []KeyLocation {
166150
var locations []KeyLocation
167-
168151
for _, path := range customPaths {
169152
if path == "" {
170-
171-
continue
172-
173-
}
153+
continue
154+
}
174155

175156
// Expand home directory
176157
if strings.HasPrefix(path, "~/") {
@@ -211,7 +192,6 @@ func (bm *BackupManager) processCustomPaths(customPaths []string) []KeyLocation
211192
})
212193
}
213194
}
214-
215195
return locations
216196
}
217197

@@ -222,37 +202,15 @@ func (bm *BackupManager) getSystemInfo() SystemInfo {
222202
if username == "" {
223203
username = os.Getenv("USERNAME")
224204
}
225-
226205
return SystemInfo{
227206
Hostname: hostname,
228207
Username: username,
229208
OS: "linux",
230209
}
231210
}
232211

233-
// prompt users for encryption password
234-
func (bm *BackupManager) getPassword() (string, error) {
235-
fmt.Print("Enter password for key encryption: ")
236-
bytePassword, err := term.ReadPassword(int(syscall.Stdin))
237-
if err != nil {
238-
return "", err
239-
}
240-
fmt.Println()
241-
242-
password := string(bytePassword)
243-
if len(password) < 8 {
244-
return "", fmt.Errorf("password must be at least 8 characters long") ////just for better recurity - can add more such conditions
245-
}
246-
247-
return password, nil
248-
}
249-
250-
//compressed tarball with the backup data
212+
//create compressed tarball with the backup data
251213
func (bm *BackupManager) createTarball(backupData *BackupData, tarballPath string) error {
252-
// if err := os.MkdirAll(filepath.Dir(tarballPath), 0755); err != nil {
253-
// return err
254-
// }
255-
256214
// Create tarball file
257215
file, err := os.Create(tarballPath)
258216
if err != nil {
@@ -296,7 +254,6 @@ func (bm *BackupManager) createTarball(backupData *BackupData, tarballPath strin
296254
func GetCustomPaths() []string {
297255
var paths []string
298256
scanner := bufio.NewScanner(os.Stdin)
299-
300257
fmt.Println("\nEnter additional key locations (one per line, empty line to finish):")
301258
fmt.Println("Examples: ~/mykeys/, /opt/certificates/, ~/.config/app/keys")
302259

@@ -310,9 +267,7 @@ func GetCustomPaths() []string {
310267
if path == "" {
311268
break
312269
}
313-
314270
paths = append(paths, path)
315271
}
316-
317272
return paths
318273
}

0 commit comments

Comments
 (0)