func envelopeEncrypt()

in pkg/berglas/berglas.go [193:219]


func envelopeEncrypt(plaintext []byte) ([]byte, []byte, error) {
	key := make([]byte, 32)
	if _, err := io.ReadFull(rand.Reader, key); err != nil {
		return nil, nil, fmt.Errorf("failed to generate random key bytes: %w", err)
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to create cipher from key: %w", err)
	}

	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to create gcm cipher: %w", err)
	}

	// Generate nonce
	nonce := make([]byte, aesgcm.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		return nil, nil, fmt.Errorf("failed to generate random nonce bytes: %w", err)
	}

	// Encrypt the ciphertext with the DEK
	ciphertext := aesgcm.Seal(nonce, nonce, plaintext, nil)

	return key, ciphertext, nil
}