I'm having trouble accessing the PublicKey
field of *rsa.PrivateKey
Whenever I call x509.MarshalPKCS1PublicKey(keyBytes.PublicKey)
in the code below, I get:
[tony@localhost app]$ go run gencsr.go
# command-line-arguments
./gencsr.go:37:90: undefined: x509.MarshalPKCS1PublicKey
As you can see, I've included the x509
package and I'm able to access keyBytes.PublicKey
and see that it's of type PublicKey
.
Sources:
crypto/x509
crypto/rsa
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"fmt"
)
var oidEmailAddress = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1}
func main() {
email := ""
subj := pkix.Name{
CommonName: "example.com",
Country: []string{"US"},
Province: []string{"New York"},
Locality: []string{"Albany"},
Organization: []string{"My Company Ltd"},
OrganizationalUnit: []string{"IT"},
}
bits := 4096
key, csr := genCSR(subj, email, bits)
fmt.Printf(key)
fmt.Printf(csr)
}
func genCSR(subj pkix.Name, email string, bits int) (pemKey, csr string) {
keyBytes, _ := rsa.GenerateKey(rand.Reader, bits)
pemPubKey := string(pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: x509.MarshalPKCS1PublicKey(keyBytes.PublicKey)}))
pemKey = string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(keyBytes)}))
fmt.Printf(pemPubKey)
rawSubj := subj.ToRDNSequence()
if len(email) > 0 {
rawSubj = append(rawSubj, []pkix.AttributeTypeAndValue{
{Type: oidEmailAddress, Value: email},
})
}
asn1Subj, _ := asn1.Marshal(rawSubj)
template := x509.CertificateRequest{
RawSubject: asn1Subj,
SignatureAlgorithm: x509.SHA256WithRSA,
}
csrBytes, _ := x509.CreateCertificateRequest(rand.Reader, &template, keyBytes)
csr = string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrBytes}))
return pemKey, csr
}