github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/config/handler/encryption.go (about)

     1  package handler
     2  
     3  import (
     4  	"crypto/aes"
     5  	"crypto/cipher"
     6  	"crypto/rand"
     7  	"encoding/hex"
     8  	"fmt"
     9  	"io"
    10  )
    11  
    12  // encrypt/decrypt functions are taken from https://www.melvinvivas.com/how-to-encrypt-and-decrypt-data-using-aes/
    13  
    14  func encrypt(stringToEncrypt string, key []byte) (string, error) {
    15  	plaintext := []byte(stringToEncrypt)
    16  
    17  	//Create a new Cipher Block from the key
    18  	block, err := aes.NewCipher(key)
    19  	if err != nil {
    20  		return "", err
    21  	}
    22  
    23  	//Create a new GCM - https://en.wikipedia.org/wiki/Galois/Counter_Mode
    24  	//https://golang.org/pkg/crypto/cipher/#NewGCM
    25  	aesGCM, err := cipher.NewGCM(block)
    26  	if err != nil {
    27  		return "", err
    28  	}
    29  
    30  	//Create a nonce. Nonce should be from GCM
    31  	nonce := make([]byte, aesGCM.NonceSize())
    32  	if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
    33  		return "", err
    34  	}
    35  
    36  	//Encrypt the data using aesGCM.Seal
    37  	//Since we don't want to save the nonce somewhere else in this case, we add it as a prefix to the encrypted data. The first nonce argument in Seal is the prefix.
    38  	ciphertext := aesGCM.Seal(nonce, nonce, plaintext, nil)
    39  	return fmt.Sprintf("%x", ciphertext), nil
    40  }
    41  
    42  func decrypt(encryptedString string, key []byte) (string, error) {
    43  	enc, _ := hex.DecodeString(encryptedString)
    44  
    45  	//Create a new Cipher Block from the key
    46  	block, err := aes.NewCipher(key)
    47  	if err != nil {
    48  		return "", err
    49  	}
    50  
    51  	//Create a new GCM
    52  	aesGCM, err := cipher.NewGCM(block)
    53  	if err != nil {
    54  		return "", err
    55  	}
    56  
    57  	//Get the nonce size
    58  	nonceSize := aesGCM.NonceSize()
    59  
    60  	//Extract the nonce from the encrypted data
    61  	nonce, ciphertext := enc[:nonceSize], enc[nonceSize:]
    62  
    63  	//Decrypt the data
    64  	plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
    65  	if err != nil {
    66  		return "", err
    67  	}
    68  
    69  	return fmt.Sprintf("%s", plaintext), nil
    70  }