123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- package common
- import (
- "context"
- "crypto/aes"
- "crypto/cipher"
- "crypto/md5"
- "encoding/hex"
- "fmt"
- "log/slog"
- "time"
- )
- import (
- md "google.golang.org/grpc/metadata"
- )
- var CstSh, _ = time.LoadLocation("Asia/Shanghai")
- const (
- LocateDateFormat = "2006-01-02"
- LocateTimeFormat = "2006-01-02 15:04:05"
- LocateMilliFormat = "2006-01-02 15:04:05.9999"
- )
- func Date() string {
- return time.Now().In(CstSh).Format(LocateDateFormat)
- }
- func Now() string {
- return time.Now().In(CstSh).Format(LocateTimeFormat)
- }
- func NowMilli() string {
- return time.Now().In(CstSh).Format(LocateMilliFormat)
- }
- func MD5(v []byte) string {
- h := md5.New()
- h.Write(v)
- re := h.Sum(nil)
- return hex.EncodeToString(re)
- }
- func GetHeader(ctx context.Context) (Product, Source, Lang, error) {
- m, ok := md.FromIncomingContext(ctx)
- if ok {
- slog.Debug("metadata.FromIncomingContext", "md", m)
- } else {
- return "", "", "", fmt.Errorf("metadata.FromIncomingContext<UNK>")
- }
- if (len(m.Get("product")) == 0) || (len(m.Get("source")) == 0) || (len(m.Get("language")) == 0) {
- return "", "", "", fmt.Errorf("metadata missing param")
- }
- return Product(m.Get("product")[0]), Source(m.Get("source")[0]), Lang(m.Get("language")[0]), nil
- }
- var dbPwKey = []byte("X3O6wVF&6*&lSVk0*504V~q7>\"k]6S'*") // 32 bytes for AES-256
- var dbPwNonceHex = "1962a6f6f9999447632c8a34"
- func EncryptGCM(key []byte, nonce []byte, plaintext []byte) ([]byte, error) {
- block, err := aes.NewCipher(key)
- if err != nil {
- return nil, err
- }
- gcm, err := cipher.NewGCM(block)
- if err != nil {
- return nil, err
- }
- ciphertext := gcm.Seal(nil, nonce, plaintext, nonce)
- return ciphertext, nil
- }
- func DecryptGCM(key []byte, nonce []byte, ciphertext []byte) ([]byte, error) {
- block, err := aes.NewCipher(key)
- if err != nil {
- return nil, err
- }
- gcm, err := cipher.NewGCM(block)
- if err != nil {
- return nil, err
- }
- plaintext, err := gcm.Open(nil, nonce, ciphertext, nonce)
- if err != nil {
- return nil, err
- }
- return plaintext, nil
- }
- func DBPwdEncrypt(ciphertext []byte) ([]byte, error) {
- nonce, _ := hex.DecodeString(dbPwNonceHex)
- return EncryptGCM(dbPwKey, nonce, ciphertext)
- }
- func DBPwdDecrypt(ciphertext []byte) ([]byte, error) {
- nonce, _ := hex.DecodeString(dbPwNonceHex)
- return DecryptGCM(dbPwKey, nonce, ciphertext)
- }
|