sign.go 2.3 KB

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