Skip to content

Instantly share code, notes, and snippets.

@subwiz
Last active January 27, 2023 03:34
Show Gist options
  • Save subwiz/6653b523073ed8cd54471afd173443e0 to your computer and use it in GitHub Desktop.
Save subwiz/6653b523073ed8cd54471afd173443e0 to your computer and use it in GitHub Desktop.
Go HTTP client using pkcs12 certificate
#!/bin/sh
## First convert .p12 cert to certificate and key .pem files:
openssl pkcs12 -in cert.p12 \
-clcerts -nokeys -out usercert.pem
openssl pkcs12 -in cert.p12 \
-nocerts -out userkey.pem -nodes
package main
import (
"crypto/tls"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)
func main() {
// Create request:
url := "https://host/path"
body := "request payload"
req, err := http.NewRequest("POST", url, strings.NewReader(body))
if err != nil {
log.Panic("Error creating new HTTP request. ", err)
}
// Create client:
cert, err := tls.LoadX509KeyPair("usercert.pem", "userkey.pem")
if err != nil {
log.Panic("Certficate load error. ", err)
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
},
}
client := &http.Client{Transport: tr}
// Now execute request:
resp, err := client.Do(req)
if err != nil {
log.Panic("Error making HTTP request using client. ", err)
}
respBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("## Response Body:\n", string(respBody))
}
@gkotian
Copy link

gkotian commented Jun 10, 2022

thanks for this gist @subwiz... it was helpful for me to set up a TLS connection with a remote server..

@stvoidit
Copy link

if errror:
40E7B731497F0000:error:0308010C:digital envelope routines:inner_evp_generic_fetch:unsupported:../crypto/evp/evp_fetch.c:349:Global default library context, Algorithm (RC2-40-CBC : 0), Properties ()

add flag -legacy

thx for this gist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment