sign.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package asign
  2. import (
  3. "crypto"
  4. "crypto/md5"
  5. "crypto/rand"
  6. "crypto/rsa"
  7. "crypto/sha1"
  8. "crypto/x509"
  9. "encoding/hex"
  10. "encoding/pem"
  11. "errors"
  12. "fmt"
  13. "strconv"
  14. "time"
  15. )
  16. // 签名规范:
  17. //
  18. // 1、表单提交方式:form-data
  19. // 2、请求头部参数
  20. // 参数1:sign(签名值,具体算法参考一下的前面算法)
  21. // 参数2:timestamp(时间戳,13位)
  22. // 3、请求体参数:
  23. // 参数1:appId(appId值,每个接入者唯一一个)
  24. // 参数2:timestamp(时间戳,13位,与上述一致)
  25. // 参数3:bizData(json字符串,举个例子,比方说要传合同编号如:{"contractNo":"0001"})
  26. // 4、签名算法:
  27. // 4.1、将上述3所属的bizData(json字符串),按照阿拉伯字母排序(如:{"ba":1,"ac":2}--->{"ac":2,"ba":1}),
  28. // 4.2、将4.1排序后的字符串,将【bizData+md5(bizData)+ appId + timestatmp】拼接后利用RSA非对称加密算法(SHA1withRSA),计算出最后的签名sign,对其base64编码,放入head的key(sign)中。
  29. func GetSignature(bizData string, appId string, privateKeyPEM string) (signatureBase64 string, timestamp string, err error) {
  30. timestamp = strconv.FormatInt(time.Now().UnixMilli(), 10)
  31. // Parse the privateKeyPEM into an RSA private key
  32. privateKeyBlock, _ := pem.Decode([]byte(privateKeyPEM))
  33. if privateKeyBlock == nil || privateKeyBlock.Type != "RSA PRIVATE KEY" {
  34. err = errors.New("签名失败: Error decoding private key PEM")
  35. return
  36. }
  37. privateKey, err := x509.ParsePKCS1PrivateKey(privateKeyBlock.Bytes)
  38. if err != nil {
  39. return
  40. }
  41. // md5(bizData)
  42. m := md5.New()
  43. m.Write([]byte(bizData))
  44. bdMd5Hx := hex.EncodeToString(m.Sum(nil))
  45. // Message to be signed
  46. message := bizData + bdMd5Hx + appId + timestamp
  47. // Sign the message using SHA1withRSA
  48. signature, err := signMessage(message, privateKey)
  49. if err != nil {
  50. fmt.Println("Error signing the message:", err)
  51. return
  52. }
  53. fmt.Println(signature)
  54. return
  55. }
  56. // signMessage signs the given message using SHA1withRSA
  57. func signMessage(message string, privateKey *rsa.PrivateKey) ([]byte, error) {
  58. hashed := sha1.Sum([]byte(message))
  59. return rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA1, hashed[:])
  60. }
  61. // verifySignature verifies the given signature for the message using SHA1withRSA
  62. // func verifySignature(message string, signature []byte, publicKey *rsa.PublicKey) bool {
  63. // hashed := sha1.Sum([]byte(message))
  64. // err := rsa.VerifyPKCS1v15(publicKey, crypto.SHA1, hashed[:], signature)
  65. // return err == nil
  66. // }