ssl-in-http/aes.go

97 lines
2.4 KiB
Go

package shttp
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"os"
)
// AESKey generates a random 32 byte AES Key
func AESKey() string {
bytes := make([]byte, 32) //generate a random 32 byte key for AES-256
if _, err := rand.Read(bytes); err != nil {
fmt.Println(err)
os.Exit(1)
}
return hex.EncodeToString(bytes)
}
// EncryptAESByte use system dynamic key if keyString = ""
func EncryptAESByte(ByteToEncrypt []byte, keyString string) ([]byte, error) {
if keyString == "" {
keyString = AESKey()
}
//Since the key is in string, we need to convert decode it to bytes
key, _ := hex.DecodeString(keyString)
//Create a new Cipher Block from the key
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//Create a new GCM
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
//Create a nonce. Nonce should be from GCM
nonce := make([]byte, aesGCM.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
//Encrypt the data using aesGCM.Seal
//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.
return aesGCM.Seal(nonce, nonce, ByteToEncrypt, nil), nil
}
func EncryptAES(stringToEncrypt string, keyString string) (string, error) {
ciphertext, err := EncryptAESByte([]byte(stringToEncrypt), keyString)
return hex.EncodeToString(ciphertext), err
}
// DecryptAESByte use system dynamic key if keyString = ""
func DecryptAESByte(encrypted []byte, keyString string) ([]byte, error) {
if keyString == "" {
keyString = AESKey()
}
key, _ := hex.DecodeString(keyString)
//Create a new Cipher Block from the key
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//Create a new GCM
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
//Get the nonce size
nonceSize := aesGCM.NonceSize()
//Extract the nonce from the encrypted data
nonce, ciphertext := encrypted[:nonceSize], encrypted[nonceSize:]
//Decrypt the data
return aesGCM.Open(nil, nonce, ciphertext, nil)
}
func DecryptAES(encryptedString string, keyString string) (string, error) {
encrypted, err := hex.DecodeString(encryptedString)
if err != nil {
panic(err.Error())
}
decrypted, err := DecryptAESByte(encrypted, keyString)
return string(decrypted), err
}