Implementation
Last updated
Last updated
Ensure you have Go installed on your system. You can download it from the official
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
)
// Function to encrypt plaintext using AES-GCM
func encrypt(plaintext, key string) (string, error) {
// Convert the key to bytes
keyBytes, err := hex.DecodeString(key)
if err != nil {
return "", fmt.Errorf("failed to decode key: %v", err)
}
// Create a new AES cipher using the key
block, err := aes.NewCipher(keyBytes)
if err != nil {
return "", fmt.Errorf("failed to create cipher: %v", err)
}
// Create a new GCM (Galois/Counter Mode)
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", fmt.Errorf("failed to create GCM: %v", err)
}
// Create a random nonce of the appropriate length
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", fmt.Errorf("failed to generate nonce: %v", err)
}
// Encrypt the plaintext using the nonce and GCM
ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
return hex.EncodeToString(ciphertext), nil
}
// Function to decrypt ciphertext using AES-GCM
func decrypt(ciphertext, key string) (string, error) {
// Convert the key and ciphertext to bytes
keyBytes, err := hex.DecodeString(key)
if err != nil {
return "", fmt.Errorf("failed to decode key: %v", err)
}
ciphertextBytes, err := hex.DecodeString(ciphertext)
if err != nil {
return "", fmt.Errorf("failed to decode ciphertext: %v", err)
}
// Create a new AES cipher using the key
block, err := aes.NewCipher(keyBytes)
if err != nil {
return "", fmt.Errorf("failed to create cipher: %v", err)
}
// Create a new GCM (Galois/Counter Mode)
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", fmt.Errorf("failed to create GCM: %v", err)
}
// Split the nonce and actual ciphertext
nonceSize := gcm.NonceSize()
nonce, ciphertextBytes := ciphertextBytes[:nonceSize], ciphertextBytes[nonceSize:]
// Decrypt the ciphertext using the nonce and GCM
plaintext, err := gcm.Open(nil, nonce, ciphertextBytes, nil)
if err != nil {
return "", fmt.Errorf("failed to decrypt: %v", err)
}
return string(plaintext), nil
}
func main() {
// Example key (32 bytes for AES-256, 16 bytes for AES-128)
key := "6368616e676520746869732070617373" // Example: "change this pass"
// Plaintext to encrypt
plaintext := "Hello, Golang Encryption!"
// Encrypt the plaintext
encrypted, err := encrypt(plaintext, key)
if err != nil {
fmt.Printf("Encryption failed: %v\n", err)
return
}
fmt.Printf("Encrypted Text: %s\n", encrypted)
// Decrypt the ciphertext
decrypted, err := decrypt(encrypted, key)
if err != nil {
fmt.Printf("Decryption failed: %v\n", err)
return
}
fmt.Printf("Decrypted Text: %s\n", decrypted)
}
OUTPUT :
Encrypted Text: 11ff3af66539bd5dea8decfbfe7dc0202eb5a82dbaf9f615e86e829ef3a4e293648a5dd72313e5f25f4c43837094c8be6ca99e3a21
Decrypted Text: Hello, Golang Encryption!