In today’s digital age, data security is more important than ever. One of the most reliable methods for securing data is through encryption, and the Advanced Encryption Standard (AES) is a widely-used algorithm for this purpose. In this blog post, we’ll explore how to implement AES encryption and decryption in Go (Golang).
Overview of AES
AES is a symmetric encryption algorithm, meaning it uses the same key for both encryption and decryption. It supports key sizes of 128, 192, and 256 bits. AES is known for its speed and security, making it a standard choice for encrypting sensitive data.
Implementing AES Encryption in Go
Let’s dive into the code to see how we can use AES to encrypt and decrypt data in Go.
Step 1: Generate a Key
First, we need to generate a secure key. The key length can be 16, 24, or 32 bytes, corresponding to 128, 192, or 256 bits.
func GenerateKey(size int) ([]byte, error) {
key := make([]byte, size)
_, err := rand.Read(key)
if err != nil {
return nil, err
}
return key, nil
}
Step 2: Encrypt the Plaintext
To encrypt data, we use the Encrypt
function. This function takes the plaintext and key as inputs and returns the encrypted text.
func Encrypt(plainText string, key []byte) (string, error) {
plaintext := []byte(plainText)
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
// Generate a random IV
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
// Encrypt the data
encrypter := cipher.NewCFBEncrypter(block, iv)
encrypter.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
Step 3: Decrypt the Ciphertext
To decrypt data, we use the Decrypt
function. This function takes the encrypted text and key as inputs and returns the decrypted text.
func Decrypt(cipherText string, key []byte) (string, error) {
ciphertext, err := base64.StdEncoding.DecodeString(cipherText)
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
if len(ciphertext) < aes.BlockSize {
return "", fmt.Errorf("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
decrypter := cipher.NewCFBDecrypter(block, iv)
decrypter.XORKeyStream(ciphertext, ciphertext)
return string(ciphertext), nil
}
Step 4: Putting It All Together
In the main
function, we generate a key, encrypt a sample plaintext, and then decrypt the resulting ciphertext.
func main() {
// Key length can be 16, 24, or 32 bytes (128, 192, or 256 bits)
key, err := GenerateKey(32)
if err != nil {
fmt.Println("Error generating key:", err)
return
}
// Example plaintext
plainText := "This is a secret message."
// Encrypt the plaintext
encryptedText, err := Encrypt(plainText, key)
if err != nil {
fmt.Println("Error encrypting:", err)
return
}
fmt.Println("Encrypted text:", encryptedText)
// Decrypt the ciphertext
decryptedText, err := Decrypt(encryptedText, key)
if err != nil {
fmt.Println("Error decrypting:", err)
return
}
fmt.Println("Decrypted text:", decryptedText)
// Optionally print the key in hex format for reference
fmt.Println("Encryption key (hex):", hex.EncodeToString(key))
}
Conclusion
In this post, we’ve walked through the process of implementing AES encryption and decryption in Go. By following these steps, you can secure sensitive data in your applications. Remember, always keep your encryption keys safe and never hard-code them in your source code.
Ready to Level Up Your Python Skills?
“EscapeMantra: The Ultimate Python Ebook” is here to guide you through every step of mastering Python. Whether you’re new to coding or looking to sharpen your skills, this ebook is packed with practical examples, hands-on exercises, and real-world projects to make learning both effective and enjoyable.
Here’s what you’ll get:
- Clear Explanations: Understand Python concepts easily with straightforward guidance.
- Engaging Projects: Work on fun projects like a Snake game and an AI Chatbot to apply what you’ve learned.
- Hands-On Practice: Build your skills with exercises designed to boost your confidence.
👉 Grab your copy. Dive in today and start mastering Python at your own pace. Don’t wait — your programming journey starts now!
🚀 Support My Work and Get More Exclusive Content! 🚀
If you found article helpful and want to see more in-depth content, tools, and exclusive resources, consider supporting me on Patreon. Your support helps me create and share valuable content, improve projects, and build a community of passionate developers.
👉 Become a Patron Today! Join here to access exclusive source codes, early project releases, and more!
Thank you for your support and for being part of this journey!