test_pji.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. package pji_client
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "crypto/rsa"
  6. "crypto/sha256"
  7. "crypto/tls"
  8. "crypto/x509"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "encoding/json"
  12. "encoding/pem"
  13. "errors"
  14. "fmt"
  15. "github.com/cloudwego/hertz/pkg/app/client"
  16. "github.com/cloudwego/hertz/pkg/protocol"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "time"
  21. )
  22. const (
  23. PEM_BEGIN = "-----BEGIN PRIVATE KEY-----\n"
  24. PEM_END = "\n-----END PRIVATE KEY-----"
  25. )
  26. // SysUserApiClient 是用于API交互的客户端结构体
  27. type SysUserApiClient struct {
  28. HttpClient *client.Client // Hertz客户端实例
  29. PrivateKey *rsa.PrivateKey // RSA私钥
  30. }
  31. // NewSysUserApiClient 创建并返回一个SysUserApiClient实例
  32. func NewSysUserApiClient(privateKey *rsa.PrivateKey) (*SysUserApiClient, error) {
  33. hClient, err := client.NewClient(client.WithTLSConfig(&tls.Config{
  34. InsecureSkipVerify: true,
  35. }))
  36. if err != nil {
  37. return nil, err
  38. }
  39. return &SysUserApiClient{
  40. HttpClient: hClient,
  41. PrivateKey: privateKey,
  42. }, nil
  43. }
  44. func ParsePrivateKey(privateKeyPEM string) (*rsa.PrivateKey, error) {
  45. privateKeyPEM = FormatPrivateKey(privateKeyPEM)
  46. //fmt.Println("privateKeyPEM", privateKeyPEM)
  47. // 2、解码私钥字节,生成加密对象
  48. block, _ := pem.Decode([]byte(privateKeyPEM))
  49. if block == nil {
  50. return nil, errors.New("私钥信息错误!")
  51. }
  52. //fmt.Println("block", block.Bytes)
  53. // 3、生成私钥对象
  54. priKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
  55. if err != nil {
  56. return nil, err
  57. }
  58. // 4. 类型断言为*RSA私钥
  59. privateKey := priKey.(*rsa.PrivateKey)
  60. return privateKey, nil
  61. }
  62. func FormatPrivateKey(privateKey string) string {
  63. if !strings.HasPrefix(privateKey, PEM_BEGIN) {
  64. privateKey = PEM_BEGIN + privateKey
  65. }
  66. if !strings.HasSuffix(privateKey, PEM_END) {
  67. privateKey = privateKey + PEM_END
  68. }
  69. return privateKey
  70. }
  71. // 辅助函数:对Map的键进行排序
  72. func sortMapByKey(m map[string]interface{}) map[string]interface{} {
  73. sortedMap := make(map[string]interface{})
  74. keys := make([]string, 0, len(m))
  75. for k := range m {
  76. keys = append(keys, k)
  77. }
  78. sort.Strings(keys)
  79. for _, k := range keys {
  80. sortedMap[k] = m[k]
  81. }
  82. return sortedMap
  83. }
  84. // 生成SHA-256哈希并进行RSA签名
  85. func (c *SysUserApiClient) generateSignature(val string) (string, error) {
  86. fmt.Println("val", val)
  87. // 签名摘要
  88. hash := sha256.New()
  89. hash.Write([]byte(val))
  90. hashed := hash.Sum(nil)
  91. fmt.Println("hashed", hashed)
  92. str := hex.EncodeToString(hashed)
  93. bytes := []byte(str)
  94. fmt.Println("str", str)
  95. fmt.Println("bytes", bytes)
  96. signedData, err := rsa.SignPKCS1v15(rand.Reader, c.PrivateKey, 0, bytes)
  97. str = hex.EncodeToString(signedData)
  98. if err != nil {
  99. return "", err
  100. }
  101. fmt.Println("base64", str)
  102. fmt.Println("base64 signedData", base64.StdEncoding.EncodeToString([]byte(str)))
  103. return base64.StdEncoding.EncodeToString([]byte(str)), nil
  104. }
  105. // 通用请求生成函数,设置通用头部信息
  106. func (c *SysUserApiClient) getHttpRequest(method string, url string, secretId string, encode string) *protocol.Request {
  107. req := protocol.AcquireRequest()
  108. req.Header.SetMethod(method)
  109. req.SetRequestURI(url)
  110. req.Header.Set("PJI-TIMESTAMP", strconv.FormatInt(time.Now().Unix(), 10))
  111. req.Header.Set("PJI-API-VERSION", "v1.0")
  112. req.Header.Set("PJI-ALGORITHM", "SHA3-256")
  113. req.Header.Set("PJI-SECRET-ID", secretId)
  114. req.Header.Set("PJI-ABSTRACT-SIGN", encode)
  115. req.Header.Set("Content-Type", "application/json")
  116. fmt.Println("req", req.Header.String())
  117. return req
  118. }
  119. // JsonPostRequest 发送带有JSON请求体的POST请求
  120. func (c *SysUserApiClient) JsonPostRequest(url string, paramMap map[string]interface{}, secretId string) (*protocol.Response, error) {
  121. paramMap = sortMapByKey(paramMap)
  122. jsonData, err := json.Marshal(paramMap)
  123. fmt.Println("jsonData", string(jsonData))
  124. if err != nil {
  125. return nil, err
  126. }
  127. str := string(jsonData)
  128. if string(jsonData) == "{}" {
  129. return nil, nil
  130. }
  131. signature, err := c.generateSignature(str)
  132. if err != nil {
  133. return nil, err
  134. }
  135. req := c.getHttpRequest("POST", url, secretId, signature)
  136. req.SetBody(jsonData)
  137. resp := protocol.AcquireResponse()
  138. ctx := context.Background()
  139. err = c.HttpClient.Do(ctx, req, resp)
  140. return resp, err
  141. }
  142. //// PutRequest 发送PUT请求
  143. //func (c *SysUserApiClient) PutRequest(url string, paramMap map[string]interface{}, secretId string) (*protocol.Response, error) {
  144. // paramMap = sortMapByKey(paramMap)
  145. //
  146. // jsonData, err := json.Marshal(paramMap)
  147. // if err != nil {
  148. // return nil, err
  149. // }
  150. //
  151. // signature, err := c.generateSignature(jsonData)
  152. // if err != nil {
  153. // return nil, err
  154. // }
  155. //
  156. // req := c.getHttpRequest("PUT", url, secretId, signature)
  157. // req.SetBody(jsonData)
  158. //
  159. // resp := protocol.AcquireResponse()
  160. // ctx := context.Background()
  161. // err = c.HttpClient.Do(ctx, req, resp)
  162. // return resp, err
  163. //}
  164. // GetRequest 发送GET请求
  165. func (c *SysUserApiClient) GetRequest(url string, paramMap map[string]string, secretId string) (*protocol.Response, error) {
  166. //sortedParams := url.Values{}
  167. //for k, v := range paramMap {
  168. // sortedParams.Add(k, v)
  169. //}
  170. //sortedURL := url + "?" + sortedParams.Encode()
  171. //jsonData, err := json.Marshal(paramMap)
  172. jsonData, err := json.Marshal(paramMap)
  173. fmt.Println("jsonData", string(jsonData))
  174. if err != nil {
  175. return nil, err
  176. }
  177. str := string(jsonData)
  178. if string(jsonData) == "{}" {
  179. str = ""
  180. }
  181. signature, err := c.generateSignature(str)
  182. if err != nil {
  183. return nil, err
  184. }
  185. req := c.getHttpRequest("GET", url, secretId, signature)
  186. resp := protocol.AcquireResponse()
  187. ctx := context.Background()
  188. err = c.HttpClient.Do(ctx, req, resp)
  189. return resp, err
  190. }
  191. //// DeleteRequest 发送DELETE请求
  192. //func (c *SysUserApiClient) DeleteRequest(url string, paramMap map[string]string, secretId string) (*protocol.Response, error) {
  193. // sortedParams := url.Values{}
  194. // for k, v := range paramMap {
  195. // sortedParams.Add(k, v)
  196. // }
  197. // sortedURL := url + "?" + sortedParams.Encode()
  198. //
  199. // jsonData, err := json.Marshal(paramMap)
  200. // if err != nil {
  201. // return nil, err
  202. // }
  203. //
  204. // signature, err := c.generateSignature(jsonData)
  205. // if err != nil {
  206. // return nil, err
  207. // }
  208. //
  209. // req := c.getHttpRequest("DELETE", sortedURL, secretId, signature)
  210. //
  211. // resp := protocol.AcquireResponse()
  212. // err = c.HttpClient.Do(req, resp)
  213. // return resp, err
  214. //}
  215. //// FormDataRequest 发送带有form-data的POST请求
  216. //func (c *SysUserApiClient) FormDataRequest(url string, paramMap map[string]string, secretId string) (*protocol.Response, error) {
  217. // paramMap = sortMapByKeyString(paramMap)
  218. //
  219. // jsonData, err := json.Marshal(paramMap)
  220. // if err != nil {
  221. // return nil, err
  222. // }
  223. //
  224. // signature, err := c.generateSignature(jsonData)
  225. // if err != nil {
  226. // return nil, err
  227. // }
  228. //
  229. // req := c.getHttpRequest("POST", url, secretId, signature)
  230. // formBody := url.Values{}
  231. // for k, v := range paramMap {
  232. // formBody.Set(k, v)
  233. // }
  234. // req.Header.SetContentType("multipart/form-data")
  235. // req.SetBody([]byte(formBody.Encode()))
  236. //
  237. // resp := protocol.AcquireResponse()
  238. // err = c.HttpClient.Do(req, resp)
  239. // return resp, err
  240. //}
  241. //// UploadRequest 上传文件
  242. //func (c *SysUserApiClient) UploadRequest(url string, paramMap map[string]string, file []byte, secretId string) (*protocol.Response, error) {
  243. // paramMap = sortMapByKeyString(paramMap)
  244. //
  245. // jsonData, err := json.Marshal(paramMap)
  246. // if err != nil {
  247. // return nil, err
  248. // }
  249. //
  250. // signature, err := c.generateSignature(jsonData)
  251. // if err != nil {
  252. // return nil, err
  253. // }
  254. //
  255. // req := c.getHttpRequest("POST", url, secretId, signature)
  256. // formBody := url.Values{}
  257. // for k, v := range paramMap {
  258. // formBody.Set(k, v)
  259. // }
  260. //
  261. // req.Header.SetContentType("multipart/form-data")
  262. // req.SetBody([]byte(formBody.Encode())) // 文件数据可以单独处理
  263. //
  264. // resp := protocol.AcquireResponse()
  265. // err = c.HttpClient.Do(req, resp)
  266. // return resp, err
  267. //}
  268. //
  269. //// DownLoadRequest 文件下载
  270. //func (c *SysUserApiClient) DownLoadRequest(url string, paramMap map[string]string, secretId string) (*protocol.Response, error) {
  271. // sortedParams := url.Values{}
  272. // for k, v := range paramMap {
  273. // sortedParams.Add(k, v)
  274. // }
  275. // sortedURL := url + "?" + sortedParams.Encode()
  276. //
  277. // jsonData, err := json.Marshal(paramMap)
  278. // if err != nil {
  279. // return nil, err
  280. // }
  281. //
  282. // signature, err := c.generateSignature(jsonData)
  283. // if err != nil {
  284. // return nil, err
  285. // }
  286. //
  287. // req := c.getHttpRequest("GET", sortedURL, secretId, signature)
  288. // req.SetBody([]byte{})
  289. //
  290. // resp := protocol.AcquireResponse()
  291. // err = c.HttpClient.Do(req, resp)
  292. // return resp, err
  293. //}
  294. // 辅助函数:对字符串Map的键进行排序
  295. func sortMapByKeyString(m map[string]string) map[string]string {
  296. sortedMap := make(map[string]string)
  297. keys := make([]string, 0, len(m))
  298. for k := range m {
  299. keys = append(keys, k)
  300. }
  301. sort.Strings(keys)
  302. for _, k := range keys {
  303. sortedMap[k] = m[k]
  304. }
  305. return sortedMap
  306. }