How to implement PHP RSA signature by go

        $pkeyid = openssl_pkey_get_private ( $priv_key );
        openssl_sign ( $params_str, $signMsg, $pkeyid, OPENSSL_ALGO_SHA1 );
        openssl_free_key ( $pkeyid );
        $signMsg = base64_encode ( $signMsg );

I would like to ask how to use GO to implement signatures like PHP. The code I wrote is as follows, which is always unsuccessful

.
func getSing(splice string, priKey []byte) (encrypt string) {
    PEMBlock, _ := pem.Decode(priKey)
    if PEMBlock == nil {
        log.Fatal("PEM")
    }
    privkey, err := x509.ParsePKCS8PrivateKey(PEMBlock.Bytes)
    if err != nil {
        log.Fatal(err)
    }
    pri, ok := privkey.(*rsa.PrivateKey)
    if ok {
        // SH256 := crypto.SHA256
        // hashed := sha256.Sum256([]byte(fmt.Sprintf("%x", sha256.Sum256([]byte(splice)))))
        // hashed := sha256.Sum256([]byte(nil))
        // sign, err := rsa.SignPKCS1v15(rand.Reader, pri, SH256, hashed[:])

        SH1 := crypto.SHA1
        // hashed := sha1.Sum([]byte(fmt.Sprintf("%x", sha1.Sum([]byte(splice)))))
        hashed := sha1.Sum([]byte(nil))
        sign, err := rsa.SignPKCS1v15(rand.Reader, pri, SH1, hashed[:])

        if err != nil {
            log.Fatal(err)
        }
        return Base64Encode(sign)
    } else {
        log.Fatal(ok)
    }
    return
}

ask everyone to help solve it. I"m sure there"s something wrong, which leads to the wrong signature, and the verification of the signature is not correct

.
Mar.10,2021

your HASH usage is wrong, please refer to the following code

/*


@author: 
*/
package main

import (
    "bytes"
    "crypto"
    "crypto/rand"
    "crypto/rsa"
    "crypto/sha512"
    "log"
)

type Demo struct {
    PriKey *rsa.PrivateKey
}

func (demo *Demo) LoadPrivateKey() {
    privateKey, err := rsa.GenerateKey(rand.Reader, 1024)
    if err != nil {
        log.Fatal(err)
    }
    demo.PriKey = privateKey
}

//  digest, signature
func (demo *Demo) Sign(message string) ([]byte, []byte) {
    messageBytes := bytes.NewBufferString(message)
    hash := sha512.New()
    hash.Write(messageBytes.Bytes())
    digest := hash.Sum(nil)

    signature, err := rsa.SignPKCS1v15(rand.Reader, demo.PriKey, crypto.SHA512, digest)
    if err != nil {
        log.Fatalf("rsa.SignPKCS1v15 error: %v\n", err)
    }
    return digest, signature
}

func (demo *Demo) Check(digest, signature []byte) bool {
    err := rsa.VerifyPKCS1v15(&demo.PriKey.PublicKey, crypto.SHA512, digest, signature)
    if err != nil {
        log.Printf("rsa.VerifyPKCS1v15 error: %V\n", err)
        return false
    }
    return true
}

func main() {
    demo := &Demo{}
    demo.LoadPrivateKey()
    digest, signature := demo.Sign("hi")
    if demo.Check(digest, signature) {
        log.Printf("signature is good")
    } else {
        log.Printf("signature is bad")
    }
}

answer correctly upstairs

Menu