AES256 encryption

Look! there's a flower!·2024년 12월 3일

Go provides built-in support for AES-256 encryption through its "crypto/aes" package. Here's a practical example of how to use AES-256 encryption and decryption:

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "encoding/base64"
    "fmt"
    "io"
)

func encrypt(plaintext []byte, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }

    // Create a new GCM
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return nil, err
    }

    // Create a nonce
    nonce := make([]byte, gcm.NonceSize())
    if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
        return nil, err
    }

    // Encrypt and seal
    return gcm.Seal(nonce, nonce, plaintext, nil), nil
}

func decrypt(ciphertext []byte, key []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
    }

    nonceSize := gcm.NonceSize()
    if len(ciphertext) < nonceSize {
        return nil, fmt.Errorf("ciphertext too short")
    }

    nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
    return gcm.Open(nil, nonce, ciphertext, nil)
}

func main() {
    // Key must be 32 bytes for AES-256
    key := make([]byte, 32)
    if _, err := rand.Read(key); err != nil {
        panic(err)
    }

    message := []byte("Hello, AES-256!")
    
    // Encrypt
    encrypted, err := encrypt(message, key)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Encrypted: %s\n", base64.StdEncoding.EncodeToString(encrypted))

    // Decrypt
    decrypted, err := decrypt(encrypted, key)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Decrypted: %s\n", string(decrypted))
}

This example uses AES-GCM (Galois/Counter Mode), which provides both confidentiality and authenticity. Some key points about the implementation:

  1. Uses crypto/aes package from the standard library
  2. Implements AES-256 (requiring a 32-byte key)
  3. Uses GCM mode which is more secure than older modes like CBC
  4. Automatically handles the IV/nonce generation
  5. Includes proper error handling

Important security considerations:

  • Always use a secure random key
  • Never reuse the same nonce with the same key
  • Store and transfer the key securely
  • Consider using key derivation functions (like PBKDF2) if working with passwords
profile
Why don't you take a look around for a moment?

0개의 댓글