mirror of
https://github.com/wonli/aqi.git
synced 2025-09-26 20:51:23 +08:00
28 lines
711 B
Go
28 lines
711 B
Go
package encrypt
|
|
|
|
import (
|
|
"crypto"
|
|
"crypto/rand"
|
|
"crypto/rsa"
|
|
"encoding/base64"
|
|
"fmt"
|
|
)
|
|
|
|
// SignSHA256WithRSA generates a signature for a string using the SHA256WithRSA algorithm with a given private key.
|
|
func SignSHA256WithRSA(source string, privateKey *rsa.PrivateKey) (signature string, err error) {
|
|
if privateKey == nil {
|
|
return "", fmt.Errorf("private key should not be nil")
|
|
}
|
|
h := crypto.Hash.New(crypto.SHA256)
|
|
_, err = h.Write([]byte(source))
|
|
if err != nil {
|
|
return "", nil
|
|
}
|
|
hashed := h.Sum(nil)
|
|
signatureByte, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return base64.StdEncoding.EncodeToString(signatureByte), nil
|
|
}
|