aes.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright © 2021-2022 Ettore Di Giacinto <[email protected]>
  2. //
  3. // This program is free software; you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation; either version 2 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program; if not, see <http://www.gnu.org/licenses/>.
  15. package crypto
  16. import (
  17. "crypto/aes"
  18. "crypto/cipher"
  19. "crypto/rand"
  20. "encoding/hex"
  21. "errors"
  22. "fmt"
  23. "io"
  24. )
  25. func AESEncrypt(plaintext string, key *[32]byte) (ciphertext string, err error) {
  26. block, err := aes.NewCipher(key[:])
  27. if err != nil {
  28. return "", err
  29. }
  30. gcm, err := cipher.NewGCM(block)
  31. if err != nil {
  32. return "", err
  33. }
  34. nonce := make([]byte, gcm.NonceSize())
  35. _, err = io.ReadFull(rand.Reader, nonce)
  36. if err != nil {
  37. return "", err
  38. }
  39. cypher := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
  40. cyp := fmt.Sprintf("%x", cypher)
  41. return cyp, nil
  42. }
  43. func AESDecrypt(text string, key *[32]byte) (plaintext string, err error) {
  44. ciphertext, _ := hex.DecodeString(text)
  45. block, err := aes.NewCipher(key[:])
  46. if err != nil {
  47. return "", err
  48. }
  49. gcm, err := cipher.NewGCM(block)
  50. if err != nil {
  51. return "", err
  52. }
  53. if len(ciphertext) < gcm.NonceSize() {
  54. return "", errors.New("malformed ciphertext")
  55. }
  56. decodedtext, err := gcm.Open(nil,
  57. ciphertext[:gcm.NonceSize()],
  58. ciphertext[gcm.NonceSize():],
  59. nil,
  60. )
  61. if err != nil {
  62. return "", err
  63. }
  64. return string(decodedtext), err
  65. }