-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencryption.go
More file actions
74 lines (60 loc) · 1.76 KB
/
Copy pathencryption.go
File metadata and controls
74 lines (60 loc) · 1.76 KB
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
70
71
72
73
74
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
)
// initEncryption derives AES-256-GCM key from token
func (d *Daemon) initEncryption() error {
// Derive 32-byte key from token using SHA256
hash := sha256.Sum256([]byte(d.token))
block, err := aes.NewCipher(hash[:])
if err != nil {
return fmt.Errorf("failed to create cipher: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return fmt.Errorf("failed to create GCM: %w", err)
}
d.aesGCM = gcm
return nil
}
// encrypt encrypts data using AES-GCM
// Returns base64(nonce || ciphertext)
func (d *Daemon) encrypt(plaintext []byte) (string, error) {
if d.aesGCM == nil {
return "", fmt.Errorf("encryption not initialized")
}
// Generate random nonce
nonce := make([]byte, d.aesGCM.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", fmt.Errorf("failed to generate nonce: %w", err)
}
// Encrypt and append to nonce
ciphertext := d.aesGCM.Seal(nonce, nonce, plaintext, nil)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
// decrypt decrypts base64(nonce || ciphertext) using AES-GCM
func (d *Daemon) decrypt(encoded string) ([]byte, error) {
if d.aesGCM == nil {
return nil, fmt.Errorf("encryption not initialized")
}
data, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return nil, fmt.Errorf("failed to decode base64: %w", err)
}
nonceSize := d.aesGCM.NonceSize()
if len(data) < nonceSize {
return nil, fmt.Errorf("ciphertext too short")
}
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plaintext, err := d.aesGCM.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, fmt.Errorf("failed to decrypt: %w", err)
}
return plaintext, nil
}