使用证书颁发机构签署证书请求

kro*_*tar 7 pki go x509certificate mutual-authentication tls1.2

我想使用TLS相互身份验证来验证在go中制作的API上的客户端.我已经创建了一个证书颁发机构,让我们说Bob有一个他希望与客户端一起使用的密钥对.Bob创建了一个证书请求,并希望我验证他的证书,以便在API上进行授权和身份验证.

我用它来创建我的证书颁发机构:

openssl genrsa -aes256 -out ca.key 4096
openssl req -new -x509 -sha256 -days 730 -key ca.key -out ca.crt
Run Code Online (Sandbox Code Playgroud)

Bob用它来创建他的证书和证书请求:

openssl genrsa -out bob.key 4096
openssl req -new -key bob.key -out bob.csr
Run Code Online (Sandbox Code Playgroud)

我想得到这个,但是在去:

openssl x509 -req -days 365 -sha256 -in bob.csr -CA ca.crt -CAkey ca.key -set_serial 3 -out bob.crt
Run Code Online (Sandbox Code Playgroud)

现在,使用theses命令,Bob可以创建一个到我的API的TLS连接,使用这个tls.Config:

func createTLSConfig(certFile string, keyFile string, clientCAFilepath string) (config *tls.Config, err error) {
    cer, err := tls.LoadX509KeyPair(certFile, keyFile)
    if err != nil {
        return nil, err
    }

    clientCAFile, err := ioutil.ReadFile(clientCAFilepath)
    if err != nil {
        return nil, err
    }
    clientCAPool := x509.NewCertPool()
    clientCAPool.AppendCertsFromPEM(clientCAFile)

    config = &tls.Config{
        Certificates: []tls.Certificate{cer},
        ClientAuth: tls.RequireAndVerifyClientCert,
        ClientCAs:  clientCAPool,
        CipherSuites: []uint16{
            tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
            tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
        },
        PreferServerCipherSuites: true,
        SessionTicketsDisabled:   false,
        MinVersion:               tls.VersionTLS12,
        CurvePreferences:         []tls.CurveID{tls.CurveP521, tls.CurveP384},
    }

    return config, nil
}
Run Code Online (Sandbox Code Playgroud)

但如果朱莉娅现在想登录怎么办?她将不得不创建一个CSR,发送给我,我也必须手动验证她的CSR到CRT.为了避免这种手动操作,我们的想法是建立一个注册终点,Julia可以提交她的CSR并获得有效的CRT.端点基本上如下所示:

func Register(c echo.Context) (err error) {
    // get Julia's csr from POST body
    csr := certificateFromBody(c.Body)

    // valid csr with ca to generate the crt
    crt := signCSR(csr, config.ClientCAPath)

    // return the crt to julia
    return c.JSON(http.StatusCreated, base64.StdEncoding.EncodeToString(crt))
}
Run Code Online (Sandbox Code Playgroud)

我花了一些时间来了解openssl如何使用CA从CRS创建CRT,但没有成功.

Golang有一个来自crypto/x509包的CertificateRequest对象,我可以使用ParseCertificateRequest创建该对象,但我找不到获取此对象和我的CA并返回证书的函数.

谢谢您的帮助!

kro*_*tar 11

它现在正常工作,这是一个基于CR的CRT验证CSR的基本解决方案:

  • 加载证书
  • 加载私钥(带密码)
  • 加载bob CSR
  • 使用CSR和CA信息创建证书模板
  • 从模板和CA私钥生成证书
  • 保存鲍勃的证书

一个工作的例子:

package main

import (
    "crypto/rand"
    "crypto/x509"
    "encoding/pem"
    "io/ioutil"
    "math/big"
    "os"
    "time"
)

func crsToCrtExample() {
    // load CA key pair
    //      public key
    caPublicKeyFile, err := ioutil.ReadFile("certs/ca-root.crt")
    if err != nil {
        panic(err)
    }
    pemBlock, _ := pem.Decode(caPublicKeyFile)
    if pemBlock == nil {
        panic("pem.Decode failed")
    }
    caCRT, err := x509.ParseCertificate(pemBlock.Bytes)
    if err != nil {
        panic(err)
    }

    //      private key
    caPrivateKeyFile, err := ioutil.ReadFile("certs/ca-mutu.key")
    if err != nil {
        panic(err)
    }
    pemBlock, _ = pem.Decode(caPrivateKeyFile)
    if pemBlock == nil {
        panic("pem.Decode failed")
    }
    der, err := x509.DecryptPEMBlock(pemBlock, []byte("ca private key password"))
    if err != nil {
        panic(err)
    }
    caPrivateKey, err := x509.ParsePKCS1PrivateKey(der)
    if err != nil {
        panic(err)
    }

    // load client certificate request
    clientCSRFile, err := ioutil.ReadFile("certs/bob.csr")
    if err != nil {
        panic(err)
    }
    pemBlock, _ = pem.Decode(clientCSRFile)
    if pemBlock == nil {
        panic("pem.Decode failed")
    }
    clientCSR, err := x509.ParseCertificateRequest(pemBlock.Bytes)
    if err != nil {
        panic(err)
    }
    if err = clientCSR.CheckSignature(); err != nil {
        panic(err)
    }

    // create client certificate template
    clientCRTTemplate := x509.Certificate{
        Signature:          clientCSR.Signature,
        SignatureAlgorithm: clientCSR.SignatureAlgorithm,

        PublicKeyAlgorithm: clientCSR.PublicKeyAlgorithm,
        PublicKey:          clientCSR.PublicKey,

        SerialNumber: big.NewInt(2),
        Issuer:       caCRT.Subject,
        Subject:      clientCSR.Subject,
        NotBefore:    time.Now(),
        NotAfter:     time.Now().Add(24 * time.Hour),
        KeyUsage:     x509.KeyUsageDigitalSignature,
        ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
    }

    // create client certificate from template and CA public key
    clientCRTRaw, err := x509.CreateCertificate(rand.Reader, &clientCRTTemplate, caCRT, clientCSR.PublicKey, caPrivateKey)
    if err != nil {
        panic(err)
    }

    // save the certificate
    clientCRTFile, err := os.Create("certs/bob.crt")
    if err != nil {
        panic(err)
    }
    pem.Encode(clientCRTFile, &pem.Block{Type: "CERTIFICATE", Bytes: clientCRTRaw})
    clientCRTFile.Close()
}
Run Code Online (Sandbox Code Playgroud)

谢谢马克!


Mar*_*ark 4

您也许可以使用x509.CreateCertificate

CreateCertificate 的参数之一是“模板”证书。

您可以使用 Julia 的CertificateRequest中的字段来设置模板证书的字段。

Go 的生成证书脚本显示了 CreateCertificate 的用法示例。

这假设来自 Julia 的 API 请求确实来自 Julia,并且有足够的可信度来签署请求并返回证书。

此外,在 Go 中使用您自己的 PKI 进行 TLS可能会有所帮助。