func PEM2PrivKey(s string) crypto.PrivateKey { p, _ := pem.Decode([]byte(s)) if p == nil { panic("no PEM block found in " + s) } // Try various different private key formats one after another. if rsaPrivKey, err := x509.ParsePKCS1PrivateKey(p.Bytes); err == nil { return *rsaPrivKey } if pkcs8Key, err := x509.ParsePKCS8PrivateKey(p.Bytes); err == nil { if reflect.TypeOf(pkcs8Key).Kind() == reflect.Ptr { pkcs8Key = reflect.ValueOf(pkcs8Key).Elem().Interface() } return pkcs8Key } return nil }
func main() { block, _ := pem.Decode([]byte(pemPrivateKey)) rsaPriv, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { panic("Failed to parse private key: " + err.Error()) } template := x509.Certificate{ SerialNumber: big.NewInt(1), Subject: pkix.Name{ CommonName: "test", Organization: []string{"Σ Acme Co"}, }, NotBefore: time.Unix(1000, 0), NotAfter: time.Unix(100000, 0), KeyUsage: x509.KeyUsageCertSign, } if _, err = x509.CreateCertificate(rand.Reader, &template, &template, &rsaPriv.PublicKey, rsaPriv); err != nil { panic("failed to create certificate with basic imports: " + err.Error()) } }