gmd5.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. // Package gmd5 provides useful API for MD5 encryption algorithms.
  7. package gmd5
  8. import (
  9. "crypto/md5"
  10. "fmt"
  11. "io"
  12. "os"
  13. "github.com/gogf/gf/util/gconv"
  14. )
  15. // Encrypt encrypts any type of variable using MD5 algorithms.
  16. // It uses gconv package to convert <v> to its bytes type.
  17. func Encrypt(data interface{}) (encrypt string, err error) {
  18. return EncryptBytes(gconv.Bytes(data))
  19. }
  20. // MustEncrypt encrypts any type of variable using MD5 algorithms.
  21. // It uses gconv package to convert <v> to its bytes type.
  22. // It panics if any error occurs.
  23. func MustEncrypt(data interface{}) string {
  24. result, err := Encrypt(data)
  25. if err != nil {
  26. panic(err)
  27. }
  28. return result
  29. }
  30. // EncryptBytes encrypts <data> using MD5 algorithms.
  31. func EncryptBytes(data []byte) (encrypt string, err error) {
  32. h := md5.New()
  33. if _, err = h.Write([]byte(data)); err != nil {
  34. return "", err
  35. }
  36. return fmt.Sprintf("%x", h.Sum(nil)), nil
  37. }
  38. // MustEncryptBytes encrypts <data> using MD5 algorithms.
  39. // It panics if any error occurs.
  40. func MustEncryptBytes(data []byte) string {
  41. result, err := EncryptBytes(data)
  42. if err != nil {
  43. panic(err)
  44. }
  45. return result
  46. }
  47. // EncryptBytes encrypts string <data> using MD5 algorithms.
  48. func EncryptString(data string) (encrypt string, err error) {
  49. return EncryptBytes([]byte(data))
  50. }
  51. // MustEncryptString encrypts string <data> using MD5 algorithms.
  52. // It panics if any error occurs.
  53. func MustEncryptString(data string) string {
  54. result, err := EncryptString(data)
  55. if err != nil {
  56. panic(err)
  57. }
  58. return result
  59. }
  60. // EncryptFile encrypts file content of <path> using MD5 algorithms.
  61. func EncryptFile(path string) (encrypt string, err error) {
  62. f, err := os.Open(path)
  63. if err != nil {
  64. return "", err
  65. }
  66. defer f.Close()
  67. h := md5.New()
  68. _, err = io.Copy(h, f)
  69. if err != nil {
  70. return "", err
  71. }
  72. return fmt.Sprintf("%x", h.Sum(nil)), nil
  73. }
  74. // MustEncryptFile encrypts file content of <path> using MD5 algorithms.
  75. // It panics if any error occurs.
  76. func MustEncryptFile(path string) string {
  77. result, err := EncryptFile(path)
  78. if err != nil {
  79. panic(err)
  80. }
  81. return result
  82. }