// Copyright 2024 Patial Tech (Ankit Patial). // // This file is part of code.patial.tech/go/appcore, which is MIT licensed. // See http://opensource.org/licenses/MIT package crypto import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "encoding/hex" "fmt" "io" ) // NewEncryptionKey will generate new key as base64 encoded string // // should be of 16, 24 or 32 bytes in length func NewEncryptionKey(size uint8) (string, error) { b, err := RandomBytes(size) if err != nil { return "", err } return base64.StdEncoding.EncodeToString(b), nil } func decodeEncryptionKey(str string) ([]byte, error) { return base64.StdEncoding.DecodeString(str) } // Encrypt text using the encyption key func Encrypt(key, text string) (string, error) { b, err := decodeEncryptionKey(key) if err != nil { return "", fmt.Errorf("decrypted base64 string: %w", err) } gcm, err := getGCM(b) if err != nil { return "", err } // create a nonce. Nonce should be from GCM nonce := make([]byte, gcm.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { return "", err } // encrypt the data using gcm.Seal ciphertext := gcm.Seal(nonce, nonce, []byte(text), nil) // prefix nonce to the ciphertext return fmt.Sprintf("%x", ciphertext), nil } // Decrypt text using the encryption key func Decrypt(key, text string) (string, error) { b, err := decodeEncryptionKey(key) if err != nil { return "", fmt.Errorf("decrypted base64 string: %w", err) } // create a new Cipher Block from the key gcm, err := getGCM(b) if err != nil { return "", err } nonceSize := gcm.NonceSize() enc, err := hex.DecodeString(text) if err != nil { return "", err } nonce, ciphertext := enc[:nonceSize], enc[nonceSize:] // decrypt plaintext, err := gcm.Open(nil, nonce, ciphertext, nil) if err != nil { return "", err } return string(plaintext), nil } func getGCM(key []byte) (gcm cipher.AEAD, err error) { // cipher block from the key b, err := aes.NewCipher(key) if err != nil { return gcm, err } // GCM - https://en.wikipedia.org/wiki/Galois/Counter_Mode // https://golang.org/pkg/crypto/cipher/#NewGCM gcm, err = cipher.NewGCM(b) if err != nil { return gcm, err } return gcm, nil }