aes.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package encrypter
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "crypto/rsa"
  7. "crypto/sha256"
  8. "encoding/base64"
  9. )
  10. // AESKey type
  11. type AESKey []byte
  12. // EncryptedAESKey type
  13. type EncryptedAESKey []byte
  14. // NewAESKey func
  15. func NewAESKey() AESKey {
  16. bb := make([]byte, 32)
  17. rand.Read(bb)
  18. return AESKey(bb)
  19. }
  20. // ParseAESKey func
  21. func ParseAESKey(b []byte) AESKey {
  22. if len(b) != 32 {
  23. slog.Panicf("Invalid AESKey (%v)", len(b))
  24. }
  25. return (AESKey)(b)
  26. }
  27. // EncryptKey func
  28. func (s *AESKey) EncryptKey(key *PublicKey) EncryptedAESKey {
  29. bb, err := key.Encrypt(([]byte)(*s))
  30. if err != nil {
  31. panic(err)
  32. }
  33. return (EncryptedAESKey)(bb)
  34. }
  35. // Encrypt func
  36. func (s *AESKey) Encrypt(data []byte) (encrypted []byte, err error) {
  37. nonce := make([]byte, 12)
  38. rand.Read(nonce)
  39. block, err := aes.NewCipher(([]byte)(*s))
  40. if err != nil {
  41. slog.Warnf("ERROR New cipher %v", err)
  42. return
  43. }
  44. gcm, err := cipher.NewGCM(block)
  45. if err != nil {
  46. slog.Warnf("ERROR New GCM %v", err)
  47. return
  48. }
  49. encrypted = append(nonce, gcm.Seal(nil, nonce, data, nil)...)
  50. return
  51. }
  52. // Decrypt func
  53. func (s *AESKey) Decrypt(data []byte) (plain []byte, err error) {
  54. block, err := aes.NewCipher(([]byte)(*s))
  55. if err != nil {
  56. slog.Warnf("ERROR New cipher %v", err)
  57. return
  58. }
  59. gcm, err := cipher.NewGCM(block)
  60. if err != nil {
  61. slog.Warnf("ERROR New GCM %v", err)
  62. return
  63. }
  64. plain, err = gcm.Open(nil, data[:12], data[12:], nil)
  65. return
  66. }
  67. // MarshalJSON func
  68. func (s *AESKey) MarshalJSON() ([]byte, error) {
  69. return []byte("\"" + base64.RawURLEncoding.EncodeToString(([]byte)(*s)) + "\""), nil
  70. }
  71. func (s *AESKey) String() string {
  72. return base64.RawURLEncoding.EncodeToString(*s)
  73. }
  74. // Decrypt func
  75. func (s *EncryptedAESKey) Decrypt(key *PrivateKey) (AESKey, error) {
  76. bb, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, (*rsa.PrivateKey)(key), ([]byte)(*s), nil)
  77. if err != nil {
  78. slog.Warnf("ERROR Decrypt %v", err)
  79. return nil, err
  80. }
  81. return (AESKey)(bb), nil
  82. }
  83. // MarshalJSON func
  84. func (s *EncryptedAESKey) MarshalJSON() ([]byte, error) {
  85. return []byte("\"" + base64.RawURLEncoding.EncodeToString(([]byte)(*s)) + "\""), nil
  86. }
  87. func (s *EncryptedAESKey) String() string {
  88. return "\"" + base64.RawURLEncoding.EncodeToString(*s) + "\""
  89. }