utils.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package common
  2. import (
  3. "context"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/md5"
  7. "encoding/hex"
  8. "fmt"
  9. "log/slog"
  10. "time"
  11. )
  12. import (
  13. md "google.golang.org/grpc/metadata"
  14. )
  15. var CstSh, _ = time.LoadLocation("Asia/Shanghai")
  16. const (
  17. LocateDateFormat = "2006-01-02"
  18. LocateTimeFormat = "2006-01-02 15:04:05"
  19. LocateMilliFormat = "2006-01-02 15:04:05.9999"
  20. )
  21. func Date() string {
  22. return time.Now().In(CstSh).Format(LocateDateFormat)
  23. }
  24. func Now() string {
  25. return time.Now().In(CstSh).Format(LocateTimeFormat)
  26. }
  27. func NowMilli() string {
  28. return time.Now().In(CstSh).Format(LocateMilliFormat)
  29. }
  30. func MD5(v []byte) string {
  31. h := md5.New()
  32. h.Write(v)
  33. re := h.Sum(nil)
  34. return hex.EncodeToString(re)
  35. }
  36. func GetHeader(ctx context.Context) (Product, Source, Lang, error) {
  37. m, ok := md.FromIncomingContext(ctx)
  38. if ok {
  39. slog.Debug("metadata.FromIncomingContext", "md", m)
  40. } else {
  41. return "", "", "", fmt.Errorf("metadata.FromIncomingContext<UNK>")
  42. }
  43. if (len(m.Get("product")) == 0) || (len(m.Get("source")) == 0) || (len(m.Get("language")) == 0) {
  44. return "", "", "", fmt.Errorf("metadata missing param")
  45. }
  46. return Product(m.Get("product")[0]), Source(m.Get("source")[0]), Lang(m.Get("language")[0]), nil
  47. }
  48. var dbPwKey = []byte("X3O6wVF&6*&lSVk0*504V~q7>\"k]6S'*") // 32 bytes for AES-256
  49. var dbPwNonceHex = "1962a6f6f9999447632c8a34"
  50. func EncryptGCM(key []byte, nonce []byte, plaintext []byte) ([]byte, error) {
  51. block, err := aes.NewCipher(key)
  52. if err != nil {
  53. return nil, err
  54. }
  55. gcm, err := cipher.NewGCM(block)
  56. if err != nil {
  57. return nil, err
  58. }
  59. ciphertext := gcm.Seal(nil, nonce, plaintext, nonce)
  60. return ciphertext, nil
  61. }
  62. func DecryptGCM(key []byte, nonce []byte, ciphertext []byte) ([]byte, error) {
  63. block, err := aes.NewCipher(key)
  64. if err != nil {
  65. return nil, err
  66. }
  67. gcm, err := cipher.NewGCM(block)
  68. if err != nil {
  69. return nil, err
  70. }
  71. plaintext, err := gcm.Open(nil, nonce, ciphertext, nonce)
  72. if err != nil {
  73. return nil, err
  74. }
  75. return plaintext, nil
  76. }
  77. func DBPwdEncrypt(ciphertext []byte) ([]byte, error) {
  78. nonce, _ := hex.DecodeString(dbPwNonceHex)
  79. return EncryptGCM(dbPwKey, nonce, ciphertext)
  80. }
  81. func DBPwdDecrypt(ciphertext []byte) ([]byte, error) {
  82. nonce, _ := hex.DecodeString(dbPwNonceHex)
  83. return DecryptGCM(dbPwKey, nonce, ciphertext)
  84. }