package crypto

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"crypto/md5"
	"encoding/hex"
	"io"
)

type Crypto struct{
	Key	string
}


func New(key string) *Crypto{
	hasher := md5.New()
	hasher.Write([]byte(key))
	return &Crypto{
		Key: hex.EncodeToString(hasher.Sum(nil)),
	}
}

func (c *Crypto) Encrypt(data string) string {
	block, _ := aes.NewCipher([]byte(c.Key))
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return ""
	}
	nonce := make([]byte, gcm.NonceSize())
	if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
		return ""
	}
	ciphertext := gcm.Seal(nonce, nonce, []byte(data), nil)
	return string(ciphertext)
}

func (c *Crypto) Decrypt(data string) string {
	key := []byte(c.Key)
	block, err := aes.NewCipher(key)
	if err != nil {
		return ""
	}
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return ""
	}
	nonceSize := gcm.NonceSize()
	nonce, ciphertext := []byte(data[:nonceSize]), []byte(data[nonceSize:])
	plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
	if err != nil {
		return ""
	}
	return string(plaintext)
}
