main.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package main
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/md5"
  7. "crypto/tls"
  8. "encoding/hex"
  9. "encoding/json"
  10. "fmt"
  11. "io/ioutil"
  12. "net/http"
  13. "time"
  14. "github.com/tidwall/gjson"
  15. )
  16. type encBlockModer struct {
  17. block cipher.Block
  18. size int
  19. }
  20. type decBlockModer struct {
  21. block cipher.Block
  22. size int
  23. }
  24. //type ecbEncrypter ecb
  25. func newBlockModer(block cipher.Block, enc bool) cipher.BlockMode {
  26. if enc {
  27. return &encBlockModer{
  28. block: block,
  29. size: block.BlockSize(),
  30. }
  31. }
  32. return &decBlockModer{
  33. block: block,
  34. size: block.BlockSize(),
  35. }
  36. }
  37. func (p *encBlockModer) BlockSize() int { return p.size }
  38. func (p *encBlockModer) CryptBlocks(dst, src []byte) {
  39. srcLen := len(src)
  40. dstLen := len(dst)
  41. if srcLen%p.size != 0 || srcLen > dstLen {
  42. return
  43. }
  44. for len(src) > 0 {
  45. p.block.Encrypt(dst, src[:p.size])
  46. src = src[p.size:]
  47. dst = dst[p.size:]
  48. }
  49. }
  50. func pkcs5Padding(src []byte, size int) []byte {
  51. padData := bytes.Repeat([]byte{byte(size - len(src)%size)}, size-len(src)%size)
  52. return append(src, padData...)
  53. }
  54. func pkcs5Trimming(src []byte) []byte {
  55. return src[:len(src)-int(src[len(src)-1])]
  56. }
  57. func AesEcbEncrypt(data []byte, key []byte) (string, error) {
  58. block, err := aes.NewCipher(key)
  59. if err != nil {
  60. return "", err
  61. }
  62. blockmoder := newBlockModer(block, true)
  63. data = pkcs5Padding(data, block.BlockSize())
  64. crypted := make([]byte, len(data))
  65. blockmoder.CryptBlocks(crypted, data)
  66. return hex.EncodeToString(crypted), nil
  67. }
  68. // func AES(src string, secret string) string {
  69. // bytes, _ := AesEncrypt(src, secret)
  70. // ret := hex.EncodeToString(bytes)
  71. // return ret
  72. // }
  73. func (p *decBlockModer) BlockSize() int { return p.size }
  74. func (p *decBlockModer) CryptBlocks(dst, src []byte) {
  75. if len(src)%p.size != 0 {
  76. return
  77. }
  78. if len(dst) < len(src) {
  79. return
  80. }
  81. for len(src) > 0 {
  82. p.block.Decrypt(dst, src[:p.size])
  83. src = src[p.size:]
  84. dst = dst[p.size:]
  85. }
  86. }
  87. func AesEcbDecrpyt(src, key string) (string, error) {
  88. if src == "" {
  89. return "", nil
  90. }
  91. crypted, err := hex.DecodeString(src)
  92. if err != nil {
  93. return "", err
  94. }
  95. block, err := aes.NewCipher([]byte(key))
  96. if err != nil {
  97. return "", err
  98. }
  99. blockModer := newBlockModer(block, false)
  100. plain := make([]byte, len(crypted))
  101. blockModer.CryptBlocks(plain, crypted)
  102. plain = pkcs5Trimming(plain)
  103. return string(plain), nil
  104. }
  105. func getParamToUrl(url string, param map[string]string) string {
  106. if len(param) == 0 {
  107. return url
  108. }
  109. str := ""
  110. for k, v := range param {
  111. str = str + "&" + k + "=" + v
  112. }
  113. if str != "" {
  114. str = "?" + str[1:]
  115. }
  116. fmt.Printf("target url is:%s\n", url+str)
  117. return url + str
  118. }
  119. func getDataConten(param map[string]string, enc bool, secret string) map[string]string {
  120. pbytes, _ := json.Marshal(param)
  121. if !enc {
  122. return param
  123. }
  124. dataConten, err := AesEcbEncrypt(pbytes, []byte(secret))
  125. if err != nil {
  126. panic(err)
  127. }
  128. m := map[string]string{
  129. "encrypt_data": dataConten,
  130. }
  131. return m
  132. }
  133. func ApiVisitBySign(param map[string]string, enc bool, url string, secret string, appKey string) {
  134. client := &http.Client{
  135. Transport: &http.Transport{
  136. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  137. },
  138. Timeout: 60 * time.Second,
  139. }
  140. fmt.Printf("appkey:%s\n", appKey)
  141. data := getDataConten(param, enc, secret)
  142. req, err := http.NewRequest("GET", getParamToUrl(url, data), nil)
  143. if err != nil {
  144. panic(err)
  145. }
  146. timestamp := time.Now().Unix()
  147. signText := fmt.Sprintf("%s%s%d", appKey, secret, timestamp)
  148. sign := MD5(signText)
  149. req.Header.Set("sign", sign)
  150. req.Header.Set("timestamp", fmt.Sprintf("%d", timestamp))
  151. req.Header.Set("appkey", appKey)
  152. req.Header.Set("appsecret", secret)
  153. req.Header.Set("Content-Type", "application/json")
  154. resp, err := client.Do(req)
  155. if err != nil {
  156. panic(err)
  157. }
  158. defer resp.Body.Close()
  159. res, err := ioutil.ReadAll(resp.Body)
  160. fmt.Printf("originRes:%s\n", res)
  161. codeExist := gjson.GetBytes(res, "code").Exists()
  162. if !codeExist {
  163. fmt.Printf("failed: originResis %s\n", res)
  164. return
  165. }
  166. code := gjson.GetBytes(res, "code").Int()
  167. if code != 0 {
  168. msg := gjson.GetBytes(res, "msg").String()
  169. fmt.Printf("api error:%d,%s\n", code, msg)
  170. return
  171. }
  172. resdata := gjson.GetBytes(res, "data").String()
  173. if enc && resdata != "" {
  174. resdata, err = AesEcbDecrpyt(resdata, secret)
  175. if err != nil {
  176. panic(err)
  177. }
  178. }
  179. fmt.Printf("success data is:%s\n", resdata)
  180. return
  181. }
  182. func ApiVisitByToken(param map[string]string, enc bool, token string, url string, secret string) {
  183. client := &http.Client{
  184. Transport: &http.Transport{
  185. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  186. },
  187. Timeout: 60 * time.Second,
  188. }
  189. data := getDataConten(param, enc, secret)
  190. req, err := http.NewRequest("GET", getParamToUrl(url, data), nil)
  191. if err != nil {
  192. panic(err)
  193. }
  194. req.Header.Set("token", token)
  195. req.Header.Set("Content-Type", "application/json")
  196. resp, err := client.Do(req)
  197. if err != nil {
  198. panic(err)
  199. }
  200. defer resp.Body.Close()
  201. res, err := ioutil.ReadAll(resp.Body)
  202. fmt.Printf("originRes:%s\n", res)
  203. codeExist := gjson.GetBytes(res, "code").Exists()
  204. if !codeExist {
  205. fmt.Printf("failed: originResis %s\n", res)
  206. return
  207. }
  208. code := gjson.GetBytes(res, "code").Int()
  209. if code != 0 {
  210. msg := gjson.GetBytes(res, "msg").String()
  211. fmt.Printf("api error:%d,%s\n", code, msg)
  212. return
  213. }
  214. resdata := gjson.GetBytes(res, "data").String()
  215. if enc && resdata != "" {
  216. resdata, err = AesEcbDecrpyt(resdata, secret)
  217. if err != nil {
  218. panic(err)
  219. }
  220. }
  221. fmt.Printf("success data is:%s\n", resdata)
  222. return
  223. }
  224. func tokenGet(tokenUrl string, user string, password string) string {
  225. m := map[string]string{
  226. "user": user,
  227. "password": password,
  228. }
  229. transport := &http.Transport{
  230. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  231. }
  232. client := &http.Client{
  233. Transport: transport,
  234. Timeout: 30 * time.Second,
  235. }
  236. req, err := http.NewRequest("GET", getParamToUrl(tokenUrl, m), nil)
  237. if err != nil {
  238. fmt.Printf("token get failed:%v\n", err)
  239. return ""
  240. }
  241. resp, err := client.Do(req)
  242. if err != nil {
  243. fmt.Printf("token get failed2:%v\n", err)
  244. return ""
  245. }
  246. defer resp.Body.Close()
  247. if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNotFound {
  248. fmt.Printf("token get failed3:%v\n", resp.StatusCode)
  249. return ""
  250. }
  251. result, err := ioutil.ReadAll(resp.Body)
  252. if err != nil {
  253. fmt.Printf("token get failed4:%v\n", err)
  254. return ""
  255. }
  256. fmt.Printf("token:%s\n", result)
  257. token := gjson.GetBytes(result, "token").String()
  258. return token
  259. }
  260. func MD5(text string) string {
  261. h := md5.New()
  262. h.Write([]byte(text))
  263. return hex.EncodeToString(h.Sum(nil))
  264. }
  265. func main() {
  266. var (
  267. // api 用户名
  268. user = "529db83441acff61a054eba562185515"
  269. // api 密码
  270. password = "DMh7lbyv"
  271. // 加密密钥
  272. secret = "1749f2a7019db090ca7c9cc69e64033c"
  273. // token url
  274. tokenUrl = "http://127.0.0.1:41002/api/v1/token"
  275. // 接口url
  276. apiUrl = "http://127.0.0.1:41002/api/v1/query/test_api"
  277. // 参数
  278. params = map[string]string{
  279. "chepai": "川A814A1",
  280. }
  281. // 是否加密
  282. crypt = false
  283. )
  284. token := tokenGet(tokenUrl, user, password)
  285. if token == "" {
  286. fmt.Printf("token is empty\n")
  287. return
  288. }
  289. //ApiVisitByToken(params, crypt, token, apiUrl, secret)
  290. ApiVisitBySign(params, crypt, apiUrl, secret, user)
  291. }