sign.go 734 B

1234567891011121314151617181920212223242526272829
  1. // Copyright 2021 Tencent Inc. All rights reserved.
  2. package utils
  3. import (
  4. "crypto"
  5. "crypto/rand"
  6. "crypto/rsa"
  7. "encoding/base64"
  8. "fmt"
  9. )
  10. // SignSHA256WithRSA 通过私钥对字符串以 SHA256WithRSA 算法生成签名信息
  11. func SignSHA256WithRSA(source string, privateKey *rsa.PrivateKey) (signature string, err error) {
  12. if privateKey == nil {
  13. return "", fmt.Errorf("private key should not be nil")
  14. }
  15. h := crypto.Hash.New(crypto.SHA256)
  16. _, err = h.Write([]byte(source))
  17. if err != nil {
  18. return "", nil
  19. }
  20. hashed := h.Sum(nil)
  21. signatureByte, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed)
  22. if err != nil {
  23. return "", err
  24. }
  25. return base64.StdEncoding.EncodeToString(signatureByte), nil
  26. }