demo.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. package huawei
  18. import (
  19. "bytes"
  20. "crypto"
  21. "crypto/rsa"
  22. "crypto/sha256"
  23. "crypto/x509"
  24. "encoding/base64"
  25. "encoding/json"
  26. "io"
  27. "net/http"
  28. "time"
  29. )
  30. // default http client with 5 seconds timeout
  31. var RequestHttpClient = http.Client{Timeout: time.Second * 5}
  32. func SendRequest(url string, bodyMap map[string]string) (string, error) {
  33. authHeaderString, err := BuildAuthorization()
  34. if err != nil {
  35. return "", err
  36. }
  37. bodyString, err := json.Marshal(bodyMap)
  38. if err != nil {
  39. return "", err
  40. }
  41. req, err := http.NewRequest("POST", url, bytes.NewReader(bodyString))
  42. if err != nil {
  43. return "", err
  44. }
  45. req.Header.Set("Content-Type", "application/json; charset=UTF-8")
  46. req.Header.Set("Authorization", authHeaderString)
  47. response, err := RequestHttpClient.Do(req)
  48. bodyBytes, err := io.ReadAll(response.Body)
  49. defer response.Body.Close()
  50. if err != nil {
  51. return "", err
  52. }
  53. return string(bodyBytes), nil
  54. }
  55. func VerifyRsaSign(content string, sign string, publicKey string) error {
  56. publicKeyByte, err := base64.StdEncoding.DecodeString(publicKey)
  57. if err != nil {
  58. return err
  59. }
  60. pub, err := x509.ParsePKIXPublicKey(publicKeyByte)
  61. if err != nil {
  62. return err
  63. }
  64. hashed := sha256.Sum256([]byte(content))
  65. signature, err := base64.StdEncoding.DecodeString(sign)
  66. if err != nil {
  67. return err
  68. }
  69. return rsa.VerifyPKCS1v15(pub.(*rsa.PublicKey), crypto.SHA256, hashed[:], signature)
  70. }