duangenshi9836 2019-07-31 17:53
浏览 106

如何使用Go在Windows上使用私钥创建和存储自签名证书

I am trying to create a self-signed certificate (including a private key) that I can store in the cert store without the help of Powershell. I am ok leveraging Windows API libraries using C but I am unfamiliar with how they work. I need to know how to create a certificate using Go and store that certificate in the certificate store on Windows.

I have tried building a certificate using Go libraries and have tried using Windows APIs a little bit

certificate.PrivateKey, certificate.Err = rsa.GenerateKey(rand.Reader, 2048)
if certificate.Err != nil {
    logger.Lg.Errorf(certificate.Err, "Failed to generate the private key")
    return
}

var serialNumber *big.Int
notBefore := time.Now()
notAfter := notBefore.Add(365 * 24 * time.Hour)

serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, certificate.Err = rand.Int(rand.Reader, serialNumberLimit)
if certificate.Err != nil {
    logger.Lg.Errorf(certificate.Err, "Failed to generate the serial number")
    return
}

template := x509.Certificate{
    SerialNumber: serialNumber,
    Subject: pkix.Name{
        Organization: []string{""},
    },
    NotBefore: notBefore,
    NotAfter:  notAfter,

    KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
    ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
    BasicConstraintsValid: true,
    IsCA:                  true,
}

certificate.DerBytes, certificate.Err = x509.CreateCertificate(rand.Reader, &template, &template, &certificate.PrivateKey.PublicKey, certificate.PrivateKey)
if certificate.Err != nil {
    logger.Lg.Errorf(certificate.Err, "Failed to create the certificate")
    return
}

info, _ := pkcs12.Encode(rand.Reader, certificate.PrivateKey, &template, nil, "")
ioutil.WriteFile("a.pfx", info, 0644)
out := base64.StdEncoding.EncodeToString(info)
fmt.Println(out)
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 keil的map文件中Image component sizes各项意思
    • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
    • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
    • ¥15 划分vlan后,链路不通了?
    • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
    • ¥15 Vue3 大型图片数据拖动排序
    • ¥15 Centos / PETGEM
    • ¥15 划分vlan后不通了
    • ¥20 用雷电模拟器安装百达屋apk一直闪退
    • ¥15 算能科技20240506咨询(拒绝大模型回答)