-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto.go
More file actions
90 lines (75 loc) · 2.47 KB
/
crypto.go
File metadata and controls
90 lines (75 loc) · 2.47 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//AES-256
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
)
// EncryptionKey is the shared secret between the agent and the server.
// It MUST be exactly 32 bytes for AES-256.
// In a real scenario, this key should be dynamically generated by the builder.
var EncryptionKey = "Passw0rd32bytesLongSecretKey!!!!"
// Encrypt encrypts the plain text using AES-256-GCM.
// It returns a Base64 encoded string containing the nonce and the ciphertext.
func Encrypt(plaintext string) (string, error) {
// 1. Create a new AES cipher block using the secret key
block, err := aes.NewCipher([]byte(EncryptionKey))
if err != nil {
return "", err
}
// 2. Wrap the block in Galois Counter Mode (GCM)
// GCM provides both encryption and authentication (integrity check).
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
// 3. Create a unique Nonce (Number used once)
// Standard nonce size for GCM is 12 bytes.
nonce := make([]byte, aesGCM.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
// 4. Encrypt and seal the data
// Seal appends the encrypted data to the nonce.
// Format: [Nonce | Ciphertext]
ciphertext := aesGCM.Seal(nonce, nonce, []byte(plaintext), nil)
// 5. Encode to Base64 to make it safe for HTTP transport (JSON compatible)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
// Decrypt decrypts the Base64 encoded ciphertext using AES-256-GCM.
func Decrypt(encryptedString string) (string, error) {
// 1. Decode the Base64 string back to bytes
data, err := base64.StdEncoding.DecodeString(encryptedString)
if err != nil {
return "", err
}
// 2. Create the AES cipher block
block, err := aes.NewCipher([]byte(EncryptionKey))
if err != nil {
return "", err
}
// 3. Create the GCM mode instance
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
// 4. Validate the data length
// The data must be at least as long as the nonce size.
nonceSize := aesGCM.NonceSize()
if len(data) < nonceSize {
return "", errors.New("ciphertext too short")
}
// 5. Separate Nonce and Ciphertext
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
// 6. Decrypt and verify the data (Open)
plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
if err != nil {
// This error occurs if the key is wrong or the data has been tampered with.
return "", fmt.Errorf("decryption failed: %v", err)
}
return string(plaintext), nil
}