123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- // Copyright © 2021-2022 Ettore Di Giacinto <[email protected]>
- //
- // This program is free software; you can redistribute it and/or modify
- // it under the terms of the GNU General Public License as published by
- // the Free Software Foundation; either version 2 of the License, or
- // (at your option) any later version.
- //
- // This program is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU General Public License for more details.
- //
- // You should have received a copy of the GNU General Public License along
- // with this program; if not, see <http://www.gnu.org/licenses/>.
- package crypto
- import (
- "crypto/aes"
- "crypto/cipher"
- "crypto/rand"
- "encoding/hex"
- "errors"
- "fmt"
- "io"
- )
- func AESEncrypt(plaintext string, key *[32]byte) (ciphertext string, err error) {
- block, err := aes.NewCipher(key[:])
- if err != nil {
- return "", err
- }
- gcm, err := cipher.NewGCM(block)
- if err != nil {
- return "", err
- }
- nonce := make([]byte, gcm.NonceSize())
- _, err = io.ReadFull(rand.Reader, nonce)
- if err != nil {
- return "", err
- }
- cypher := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
- cyp := fmt.Sprintf("%x", cypher)
- return cyp, nil
- }
- func AESDecrypt(text string, key *[32]byte) (plaintext string, err error) {
- ciphertext, _ := hex.DecodeString(text)
- block, err := aes.NewCipher(key[:])
- if err != nil {
- return "", err
- }
- gcm, err := cipher.NewGCM(block)
- if err != nil {
- return "", err
- }
- if len(ciphertext) < gcm.NonceSize() {
- return "", errors.New("malformed ciphertext")
- }
- decodedtext, err := gcm.Open(nil,
- ciphertext[:gcm.NonceSize()],
- ciphertext[gcm.NonceSize():],
- nil,
- )
- if err != nil {
- return "", err
- }
- return string(decodedtext), err
- }
|