猿问

如何在 golang 中读取 pkcs12 内容,我在 PHP 中有示例

有解密和签名接口。我想从 PHP 迁移到 Golang。PHP函数如下:


function getSignature($param){

if (is_string($param)) {

    $file_private = 'file.p12';

    if (!$cert_store = file_get_contents($file_private)) {

        return "Error: Unable to read the cert file\n";

    }

    $signature = "";

    $algo = "sha256WithRSAEncryption";

    $password = "PASSWORD";

    $private_key_file = openssl_pkcs12_read($cert_store, $cert_info, $password);

    if ($private_key_file)

    {

        $private_key = $cert_info['pkey'];

        openssl_sign($param, $signature, $private_key, $algo);

        return htmlentities(base64_encode($signature));

    }


}

return false;

}

我想用golang来实现。我怎样才能转换成golang?


解决了


这实际上是我在 golang 中的代码:


func Sign(privateKey *rsa.PrivateKey, data string) (string, error) {

h := crypto.SHA256.New()

h.Write([]byte(data))

hashed := h.Sum(nil)


sign, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed)

if err != nil {

    return "", err

}

return base64.RawURLEncoding.EncodeToString(sign), err

}



func read_keys() {

b, err := ioutil.ReadFile("file.p12")

if err != nil {

    fmt.Println(err)


}

password := "PASSWORD"

privk, _, err := pkcs12.Decode(b, password)

if err != nil {

    fmt.Println(err)

}

pv := privk.(*rsa.PrivateKey)

sign, _ := Sign(pv, "Your String Data")

fmt.Print(sign)

}


PIPIONE
浏览 247回答 1
1回答

慕婉清6462132

这是您要找的包裹data, err := ioutil.ReadFile(*in)if err != nil {    log.Fatal(err)}privateKey, certificate, err := pkcs12.Decode(data, *password)if err != nil {    log.Fatal(err)}pv := privateKey.(*rsa.PrivateKey)signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, rypto.SHA256, hash)if err != nil {    log.Fatal(err)}
随时随地看视频慕课网APP

相关分类

Go
我要回答