cryptionhandler.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. package handler
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/base64"
  6. "errors"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "git.i2edu.net/i2/go-zero/core/codec"
  12. "git.i2edu.net/i2/go-zero/core/logx"
  13. )
  14. const maxBytes = 1 << 20 // 1 MiB
  15. var errContentLengthExceeded = errors.New("content length exceeded")
  16. // CryptionHandler returns a middleware to handle cryption.
  17. func CryptionHandler(key []byte) func(http.Handler) http.Handler {
  18. return func(next http.Handler) http.Handler {
  19. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  20. cw := newCryptionResponseWriter(w)
  21. defer cw.flush(key)
  22. if r.ContentLength <= 0 {
  23. next.ServeHTTP(cw, r)
  24. return
  25. }
  26. if err := decryptBody(key, r); err != nil {
  27. w.WriteHeader(http.StatusBadRequest)
  28. return
  29. }
  30. next.ServeHTTP(cw, r)
  31. })
  32. }
  33. }
  34. func decryptBody(key []byte, r *http.Request) error {
  35. if r.ContentLength > maxBytes {
  36. return errContentLengthExceeded
  37. }
  38. var content []byte
  39. var err error
  40. if r.ContentLength > 0 {
  41. content = make([]byte, r.ContentLength)
  42. _, err = io.ReadFull(r.Body, content)
  43. } else {
  44. content, err = ioutil.ReadAll(io.LimitReader(r.Body, maxBytes))
  45. }
  46. if err != nil {
  47. return err
  48. }
  49. content, err = base64.StdEncoding.DecodeString(string(content))
  50. if err != nil {
  51. return err
  52. }
  53. output, err := codec.EcbDecrypt(key, content)
  54. if err != nil {
  55. return err
  56. }
  57. var buf bytes.Buffer
  58. buf.Write(output)
  59. r.Body = ioutil.NopCloser(&buf)
  60. return nil
  61. }
  62. type cryptionResponseWriter struct {
  63. http.ResponseWriter
  64. buf *bytes.Buffer
  65. }
  66. func newCryptionResponseWriter(w http.ResponseWriter) *cryptionResponseWriter {
  67. return &cryptionResponseWriter{
  68. ResponseWriter: w,
  69. buf: new(bytes.Buffer),
  70. }
  71. }
  72. func (w *cryptionResponseWriter) Flush() {
  73. if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
  74. flusher.Flush()
  75. }
  76. }
  77. func (w *cryptionResponseWriter) Header() http.Header {
  78. return w.ResponseWriter.Header()
  79. }
  80. // Hijack implements the http.Hijacker interface.
  81. // This expands the Response to fulfill http.Hijacker if the underlying http.ResponseWriter supports it.
  82. func (w *cryptionResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  83. if hijacked, ok := w.ResponseWriter.(http.Hijacker); ok {
  84. return hijacked.Hijack()
  85. }
  86. return nil, nil, errors.New("server doesn't support hijacking")
  87. }
  88. func (w *cryptionResponseWriter) Write(p []byte) (int, error) {
  89. return w.buf.Write(p)
  90. }
  91. func (w *cryptionResponseWriter) WriteHeader(statusCode int) {
  92. w.ResponseWriter.WriteHeader(statusCode)
  93. }
  94. func (w *cryptionResponseWriter) flush(key []byte) {
  95. if w.buf.Len() == 0 {
  96. return
  97. }
  98. content, err := codec.EcbEncrypt(key, w.buf.Bytes())
  99. if err != nil {
  100. w.WriteHeader(http.StatusInternalServerError)
  101. return
  102. }
  103. body := base64.StdEncoding.EncodeToString(content)
  104. if n, err := io.WriteString(w.ResponseWriter, body); err != nil {
  105. logx.Errorf("write response failed, error: %s", err)
  106. } else if n < len(content) {
  107. logx.Errorf("actual bytes: %d, written bytes: %d", len(content), n)
  108. }
  109. }