utils.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package common
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/md5"
  6. "encoding/hex"
  7. "time"
  8. )
  9. var CstSh, _ = time.LoadLocation("Asia/Shanghai")
  10. const (
  11. LocateDateFormat = "2006-01-02"
  12. LocateTimeFormat = "2006-01-02 15:04:05"
  13. LocateMilliFormat = "2006-01-02 15:04:05.9999"
  14. )
  15. func Date() string {
  16. return time.Now().In(CstSh).Format(LocateDateFormat)
  17. }
  18. func Now() string {
  19. return time.Now().In(CstSh).Format(LocateTimeFormat)
  20. }
  21. func NowMilli() string {
  22. return time.Now().In(CstSh).Format(LocateMilliFormat)
  23. }
  24. func MD5(v []byte) string {
  25. h := md5.New()
  26. h.Write(v)
  27. re := h.Sum(nil)
  28. return hex.EncodeToString(re)
  29. }
  30. var dbPwKey = []byte("X3O6wVF&6*&lSVk0*504V~q7>\"k]6S'*") // 32 bytes for AES-256
  31. var dbPwNonceHex = "1962a6f6f9999447632c8a34"
  32. func EncryptGCM(key []byte, nonce []byte, plaintext []byte) ([]byte, error) {
  33. block, err := aes.NewCipher(key)
  34. if err != nil {
  35. return nil, err
  36. }
  37. gcm, err := cipher.NewGCM(block)
  38. if err != nil {
  39. return nil, err
  40. }
  41. ciphertext := gcm.Seal(nil, nonce, plaintext, nonce)
  42. return ciphertext, nil
  43. }
  44. func DecryptGCM(key []byte, nonce []byte, ciphertext []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. plaintext, err := gcm.Open(nil, nonce, ciphertext, nonce)
  54. if err != nil {
  55. return nil, err
  56. }
  57. return plaintext, nil
  58. }
  59. func DBPwdEncrypt(ciphertext []byte) ([]byte, error) {
  60. nonce, _ := hex.DecodeString(dbPwNonceHex)
  61. return EncryptGCM(dbPwKey, nonce, ciphertext)
  62. }
  63. func DBPwdDecrypt(ciphertext []byte) ([]byte, error) {
  64. nonce, _ := hex.DecodeString(dbPwNonceHex)
  65. return DecryptGCM(dbPwKey, nonce, ciphertext)
  66. }