-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto.go
More file actions
67 lines (55 loc) · 1.78 KB
/
Copy pathcrypto.go
File metadata and controls
67 lines (55 loc) · 1.78 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
package netpipe
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"fmt"
"io"
)
// encrypt encrypts plaintext using AES-256-GCM.
// The key can be any length - it is hashed to exactly 32 bytes with SHA-256.
// Returns: [12 bytes nonce][ciphertext + GCM auth tag]
func encrypt(plaintext []byte, key string) ([]byte, error) {
// derive a fixed 32-byte key from whatever the developer passes
keyHash := sha256.Sum256([]byte(key))
block, err := aes.NewCipher(keyHash[:])
if err != nil {
return nil, fmt.Errorf("netpipe: aes cipher: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("netpipe: gcm: %w", err)
}
// random nonce - never reuse with the same key
nonce := make([]byte, gcm.NonceSize()) // 12 bytes for GCM
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, fmt.Errorf("netpipe: random nonce: %w", err)
}
// Seal appends ciphertext + auth tag after the nonce
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
return ciphertext, nil
}
// decrypt decrypts data produced by encrypt().
// Expects: [12 bytes nonce][ciphertext + GCM auth tag]
func decrypt(data []byte, key string) ([]byte, error) {
keyHash := sha256.Sum256([]byte(key))
block, err := aes.NewCipher(keyHash[:])
if err != nil {
return nil, fmt.Errorf("netpipe: aes cipher: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("netpipe: gcm: %w", err)
}
nonceSize := gcm.NonceSize()
if len(data) < nonceSize {
return nil, fmt.Errorf("netpipe: ciphertext too short")
}
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, fmt.Errorf("netpipe: decrypt failed (wrong key?): %w", err)
}
return plaintext, nil
}