dongshadu4498 2018-10-12 08:56
浏览 794
已采纳

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

There is a decryption and signature interface. I want to move from PHP to Golang. The PHP function is as follows:

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
";
    }
    $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;
}

I want to use golang to achieve. How can I convert into golang?

SOLVED

This is what actually my code in 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)
}
  • 写回答

1条回答 默认 最新

  • douzhe3516 2018-10-12 09:26
    关注

    this is the package you're looking for

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 有偿寻云闪付SDK转URL技术
  • ¥30 基于信创PC发布的QT应用如何跨用户启动后输入中文
  • ¥20 非root手机,如何精准控制手机流量消耗的大小,如20M
  • ¥15 远程安装一下vasp
  • ¥15 自己做的代码上传图片时,报错
  • ¥15 Lingo线性规划模型怎么搭建
  • ¥15 关于#python#的问题,请各位专家解答!区间型正向化
  • ¥15 unity从3D升级到urp管线,打包ab包后,材质全部变紫色
  • ¥50 comsol温度场仿真无法模拟微米级激光光斑
  • ¥15 上传图片时提交的存储类型