utils.go 2.0 KB

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