AFAIRE
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
crypto/crypto.go

125 lines
2.8 KiB

/*
------------------------------------------------------------------------------------------------------------------------
####### crypto ####### Copyright (c) 2021-2022 losyme ############################################## MIT License #######
------------------------------------------------------------------------------------------------------------------------
*/
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"io"
"forge.chapril.org/losyme/errors"
)
type Crypto struct {
key []byte
}
func New() *Crypto {
return &Crypto{
key: []byte{
0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF,
},
}
}
func (c *Crypto) SetKey(key string) error {
hasher := sha256.New()
if _, err := hasher.Write([]byte(key)); err != nil {
return err
}
c.key = hasher.Sum(nil)
return nil
}
func (c *Crypto) Encrypt(data []byte) ([]byte, error) {
block, err := aes.NewCipher(c.key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, data, nil), nil
}
func (c *Crypto) EncryptString(text string) (string, error) {
data, err := c.Encrypt([]byte(text))
if err != nil {
return "", errors.WithMessage(err, "unable to encrypt the string") /////////////////////////////////////////////
}
return base64.StdEncoding.EncodeToString(data), nil
}
func (c *Crypto) Decrypt(data []byte) ([]byte, error) {
block, err := aes.NewCipher(c.key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if nonceSize > len(data) {
return nil, errors.New("not enough data") //////////////////////////////////////////////////////////////////////
}
nonce, cipherData := data[:nonceSize], data[nonceSize:]
plainData, err := gcm.Open(nil, nonce, cipherData, nil)
if err != nil {
return nil, err
}
return plainData, nil
}
func (c *Crypto) DecryptString(text string) (string, error) {
decoded, err := base64.StdEncoding.DecodeString(text)
if err != nil {
return "", errors.WithMessage( /////////////////////////////////////////////////////////////////////////////////
err,
"unable to decode this string",
"string", text,
)
}
data, err := c.Decrypt(decoded)
if err != nil {
return "", errors.WithMessage( /////////////////////////////////////////////////////////////////////////////////
err,
"unable to decrypt this string",
"string", text,
)
}
return string(data), nil
}
/*
######################################################################################################## @(°_°)@ #######
*/