-
Hi, I am trying to use this library to get cert and key from p12 file and using it as tls config in http request. key, certtificate, _ := pkcs12.Decode(rawDecodedCert, certPassword) Could you give me an example of how to use/convert the key and certificate to the cert object that is used in &tls.Config? Thanks, |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Instead of using Supposing that certs is something like var raw [][]byte
for _, crt := range certs {
raw = append(raw, crt.Raw)
}
clientCert := tls.Certificate{
Certificate: raw,
PrivateKey: key,
Leaf: certs[0],
}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.TLSClientConfig = &tls.Config{
Certificates: []tls.Certificate{clientCert},
MinVersion: tls.VersionTLS12,
}
client := http.Client{
Transport: transport,
} Note that in some cases, you will need more than one intermediate. If you're using a Root certificate that is not installed in your OS, you will need to set pool := x509.NewCertPool()
pool.AddCert(root)
var raw [][]byte
for _, crt := range certs {
raw = append(raw, crt.Raw)
}
clientCert := tls.Certificate{
Certificate: raw,
PrivateKey: key,
Leaf: certs[0],
}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.TLSClientConfig = &tls.Config{
Certificates: []tls.Certificate{clientCert},
RootCAs: pool,
MinVersion: tls.VersionTLS12,
}
client := http.Client{
Transport: transport,
} Both the root and intermediates can be present in the p12 file. The DecodeChain method looks like: func DecodeChain(pfxData []byte, password string) (privateKey interface{}, certificate *x509.Certificate, caCerts []*x509.Certificate, err error) Here root := caCerts[len(caCerts)-1]
certs := append([]*x509.Certificate{certificate}, caCerts[:len(caCerts)-1]...) |
Beta Was this translation helpful? Give feedback.
-
Here's how to decode a PKCS#12 file into a key, leafCert, chainCerts, err := pkcs12.DecodeChain(rawDecodedCert, certPassword)
if err != nil {
// handle err
}
raw := [][]byte{leafCert.Raw}
for _, chainCert := range chainCerts {
raw = append(raw, chainCert.Raw)
}
tlsCert := tls.Certificate{
Certificate: raw,
PrivateKey: key,
Leaf: leafCert,
} |
Beta Was this translation helpful? Give feedback.
-
I tried your suggestions and it worked! Thanks a lot! |
Beta Was this translation helpful? Give feedback.
Here's how to decode a PKCS#12 file into a
tls.Certificate
: