aes_encryptor.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package repository
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "fmt"
  9. "io"
  10. "github.com/Wei-Shaw/sub2api/internal/config"
  11. "github.com/Wei-Shaw/sub2api/internal/service"
  12. )
  13. // AESEncryptor implements SecretEncryptor using AES-256-GCM
  14. type AESEncryptor struct {
  15. key []byte
  16. }
  17. // NewAESEncryptor creates a new AES encryptor
  18. func NewAESEncryptor(cfg *config.Config) (service.SecretEncryptor, error) {
  19. key, err := hex.DecodeString(cfg.Totp.EncryptionKey)
  20. if err != nil {
  21. return nil, fmt.Errorf("invalid totp encryption key: %w", err)
  22. }
  23. if len(key) != 32 {
  24. return nil, fmt.Errorf("totp encryption key must be 32 bytes (64 hex chars), got %d bytes", len(key))
  25. }
  26. return &AESEncryptor{key: key}, nil
  27. }
  28. // Encrypt encrypts plaintext using AES-256-GCM
  29. // Output format: base64(nonce + ciphertext + tag)
  30. func (e *AESEncryptor) Encrypt(plaintext string) (string, error) {
  31. block, err := aes.NewCipher(e.key)
  32. if err != nil {
  33. return "", fmt.Errorf("create cipher: %w", err)
  34. }
  35. gcm, err := cipher.NewGCM(block)
  36. if err != nil {
  37. return "", fmt.Errorf("create gcm: %w", err)
  38. }
  39. // Generate a random nonce
  40. nonce := make([]byte, gcm.NonceSize())
  41. if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
  42. return "", fmt.Errorf("generate nonce: %w", err)
  43. }
  44. // Encrypt the plaintext
  45. // Seal appends the ciphertext and tag to the nonce
  46. ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
  47. // Encode as base64
  48. return base64.StdEncoding.EncodeToString(ciphertext), nil
  49. }
  50. // Decrypt decrypts ciphertext using AES-256-GCM
  51. func (e *AESEncryptor) Decrypt(ciphertext string) (string, error) {
  52. // Decode from base64
  53. data, err := base64.StdEncoding.DecodeString(ciphertext)
  54. if err != nil {
  55. return "", fmt.Errorf("decode base64: %w", err)
  56. }
  57. block, err := aes.NewCipher(e.key)
  58. if err != nil {
  59. return "", fmt.Errorf("create cipher: %w", err)
  60. }
  61. gcm, err := cipher.NewGCM(block)
  62. if err != nil {
  63. return "", fmt.Errorf("create gcm: %w", err)
  64. }
  65. nonceSize := gcm.NonceSize()
  66. if len(data) < nonceSize {
  67. return "", fmt.Errorf("ciphertext too short")
  68. }
  69. // Extract nonce and ciphertext
  70. nonce, ciphertextData := data[:nonceSize], data[nonceSize:]
  71. // Decrypt
  72. plaintext, err := gcm.Open(nil, nonce, ciphertextData, nil)
  73. if err != nil {
  74. return "", fmt.Errorf("decrypt: %w", err)
  75. }
  76. return string(plaintext), nil
  77. }