utils.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. // Package utils provides some common utility methods
  2. package utils
  3. import (
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/ecdsa"
  7. "crypto/elliptic"
  8. "crypto/rand"
  9. "crypto/rsa"
  10. "crypto/x509"
  11. "encoding/hex"
  12. "encoding/pem"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "io/ioutil"
  17. "net"
  18. "os"
  19. "strings"
  20. "time"
  21. "golang.org/x/crypto/ssh"
  22. )
  23. const logSender = "utils"
  24. // IsStringInSlice searches a string in a slice and returns true if the string is found
  25. func IsStringInSlice(obj string, list []string) bool {
  26. for _, v := range list {
  27. if v == obj {
  28. return true
  29. }
  30. }
  31. return false
  32. }
  33. // IsStringPrefixInSlice searches a string prefix in a slice and returns true
  34. // if a matching prefix is found
  35. func IsStringPrefixInSlice(obj string, list []string) bool {
  36. for _, v := range list {
  37. if strings.HasPrefix(obj, v) {
  38. return true
  39. }
  40. }
  41. return false
  42. }
  43. // GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct
  44. func GetTimeAsMsSinceEpoch(t time.Time) int64 {
  45. return t.UnixNano() / 1000000
  46. }
  47. // GetTimeFromMsecSinceEpoch return a time struct from a unix timestamp with millisecond precision
  48. func GetTimeFromMsecSinceEpoch(msec int64) time.Time {
  49. return time.Unix(0, msec*1000000)
  50. }
  51. // GetAppVersion returns VersionInfo struct
  52. func GetAppVersion() VersionInfo {
  53. return versionInfo
  54. }
  55. // GetDurationAsString returns a string representation for a time.Duration
  56. func GetDurationAsString(d time.Duration) string {
  57. d = d.Round(time.Second)
  58. h := d / time.Hour
  59. d -= h * time.Hour
  60. m := d / time.Minute
  61. d -= m * time.Minute
  62. s := d / time.Second
  63. if h > 0 {
  64. return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
  65. }
  66. return fmt.Sprintf("%02d:%02d", m, s)
  67. }
  68. // ByteCountSI returns humanized size in SI (decimal) format
  69. func ByteCountSI(b int64) string {
  70. return byteCount(b, 1000)
  71. }
  72. // ByteCountIEC returns humanized size in IEC (binary) format
  73. func ByteCountIEC(b int64) string {
  74. return byteCount(b, 1024)
  75. }
  76. func byteCount(b int64, unit int64) string {
  77. if b < unit {
  78. return fmt.Sprintf("%d B", b)
  79. }
  80. div, exp := unit, 0
  81. for n := b / unit; n >= unit; n /= unit {
  82. div *= unit
  83. exp++
  84. }
  85. if unit == 1000 {
  86. return fmt.Sprintf("%.1f %cB",
  87. float64(b)/float64(div), "KMGTPE"[exp])
  88. }
  89. return fmt.Sprintf("%.1f %ciB",
  90. float64(b)/float64(div), "KMGTPE"[exp])
  91. }
  92. // GetIPFromRemoteAddress returns the IP from the remote address.
  93. // If the given remote address cannot be parsed it will be returned unchanged
  94. func GetIPFromRemoteAddress(remoteAddress string) string {
  95. ip, _, err := net.SplitHostPort(remoteAddress)
  96. if err == nil {
  97. return ip
  98. }
  99. return remoteAddress
  100. }
  101. // NilIfEmpty returns nil if the input string is empty
  102. func NilIfEmpty(s string) *string {
  103. if len(s) == 0 {
  104. return nil
  105. }
  106. return &s
  107. }
  108. // EncryptData encrypts data using the given key
  109. func EncryptData(data string) (string, error) {
  110. var result string
  111. key := make([]byte, 16)
  112. if _, err := io.ReadFull(rand.Reader, key); err != nil {
  113. return result, err
  114. }
  115. keyHex := hex.EncodeToString(key)
  116. block, err := aes.NewCipher([]byte(keyHex))
  117. if err != nil {
  118. return result, err
  119. }
  120. gcm, err := cipher.NewGCM(block)
  121. if err != nil {
  122. return result, err
  123. }
  124. nonce := make([]byte, gcm.NonceSize())
  125. if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
  126. return result, err
  127. }
  128. ciphertext := gcm.Seal(nonce, nonce, []byte(data), nil)
  129. result = fmt.Sprintf("$aes$%s$%x", keyHex, ciphertext)
  130. return result, err
  131. }
  132. // RemoveDecryptionKey returns encrypted data without the decryption key
  133. func RemoveDecryptionKey(encryptData string) string {
  134. vals := strings.Split(encryptData, "$")
  135. if len(vals) == 4 {
  136. return fmt.Sprintf("$%v$%v", vals[1], vals[3])
  137. }
  138. return encryptData
  139. }
  140. // DecryptData decrypts data encrypted using EncryptData
  141. func DecryptData(data string) (string, error) {
  142. var result string
  143. vals := strings.Split(data, "$")
  144. if len(vals) != 4 {
  145. return "", errors.New("data to decrypt is not in the correct format")
  146. }
  147. key := vals[2]
  148. encrypted, err := hex.DecodeString(vals[3])
  149. if err != nil {
  150. return result, err
  151. }
  152. block, err := aes.NewCipher([]byte(key))
  153. if err != nil {
  154. return result, err
  155. }
  156. gcm, err := cipher.NewGCM(block)
  157. if err != nil {
  158. return result, err
  159. }
  160. nonceSize := gcm.NonceSize()
  161. nonce, ciphertext := encrypted[:nonceSize], encrypted[nonceSize:]
  162. plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
  163. if err != nil {
  164. return result, err
  165. }
  166. return string(plaintext), nil
  167. }
  168. // GenerateRSAKeys generate rsa private and public keys and write the
  169. // private key to specified file and the public key to the specified
  170. // file adding the .pub suffix
  171. func GenerateRSAKeys(file string) error {
  172. key, err := rsa.GenerateKey(rand.Reader, 4096)
  173. if err != nil {
  174. return err
  175. }
  176. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  177. if err != nil {
  178. return err
  179. }
  180. defer o.Close()
  181. priv := &pem.Block{
  182. Type: "RSA PRIVATE KEY",
  183. Bytes: x509.MarshalPKCS1PrivateKey(key),
  184. }
  185. if err := pem.Encode(o, priv); err != nil {
  186. return err
  187. }
  188. pub, err := ssh.NewPublicKey(&key.PublicKey)
  189. if err != nil {
  190. return err
  191. }
  192. return ioutil.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  193. }
  194. // GenerateECDSAKeys generate ecdsa private and public keys and write the
  195. // private key to specified file and the public key to the specified
  196. // file adding the .pub suffix
  197. func GenerateECDSAKeys(file string) error {
  198. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  199. if err != nil {
  200. return err
  201. }
  202. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  203. if err != nil {
  204. return err
  205. }
  206. defer o.Close()
  207. keyBytes, err := x509.MarshalECPrivateKey(key)
  208. if err != nil {
  209. return err
  210. }
  211. priv := &pem.Block{
  212. Type: "EC PRIVATE KEY",
  213. Bytes: keyBytes,
  214. }
  215. if err := pem.Encode(o, priv); err != nil {
  216. return err
  217. }
  218. pub, err := ssh.NewPublicKey(&key.PublicKey)
  219. if err != nil {
  220. return err
  221. }
  222. return ioutil.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
  223. }