go / expert
Snippet
Authentifizierte kryptografische Verschlüsselung mittels AES-GCM-Chiffrenkonstrukten
Das Standardpaket `crypto/cipher` bietet den Galois/Counter Mode (GCM) für authentifizierte Verschlüsselung. AES-GCM garantiert sowohl Vertraulichkeit als auch kryptografische Authentizität durch zufällige Nonces und Authentifizierungstags.
snippet.go
go
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
package mainimport ("crypto/aes""crypto/cipher""crypto/rand""fmt""io")func EncryptAESGCM(key []byte, plaintext []byte) ([]byte, error) {block, err := aes.NewCipher(key)if err != nil {return nil, err}gcm, err := cipher.NewGCM(block)if err != nil {return nil, err}nonce := make([]byte, gcm.NonceSize())if _, err := io.ReadFull(rand.Reader, nonce); err != nil {return nil, err}return gcm.Seal(nonce, nonce, plaintext, nil), nil}func main() {key := make([]byte, 32)rand.Read(key)cipherText, _ := EncryptAESGCM(key, []byte("confidential payload"))fmt.Printf("Encrypted output byte length: %d\n", len(cipherText))}
Erklärung
1
gcm, err := cipher.NewGCM(block)
Erzeugt eine Galois/Counter Mode (GCM) authentifizierte Chiffre zum Schutz vor Manipulation des Geheimtextes.
2
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
Füllt das Nonce-Array mit kryptografisch sicheren Zufallsbytes aus crypto/rand.Reader.
3
return gcm.Seal(nonce, nonce, plaintext, nil), nil
Verschlüsselt Daten, fügt ein Authentifizierungstag hinzu und stellt die eindeutige Nonce voran.