I'd like to generate some certificates by golang, but stuck with a problem.
When I do that in php, it maybe like those codes:
$privkey = openssl_pkey_new([
'digest_alg' => 'des3',
'private_key_bits' => 1024,
'private_key_type' => OPENSSL_KEYTYPE_RSA
]);
$csr = openssl_csr_new([
"countryName" => "EN",
"stateOrProvinceName" => "province",
"localityName" => "city",
"organizationName" => "org",
"organizationalUnitName" => "org",
"commonName" => "name",
], $privkey, ['digest_alg' => 'des3']);
$x509 = openssl_csr_sign($csr, null, $privkey, $days=3650, ['digest_alg' => 'des3']);
openssl_x509_export_to_file($x509, "/path/to/pub.cer");
openssl_pkcs12_export_to_file($x509, "/path/to/pri.pfx", $privkey, "password");
And now with golang I can only create the private key but don't know what to do next.Help me please and many thanks.
func main() {
keyBytes, err := rsa.GenerateKey(rand.Reader, bitSize)
if err != nil {
panic(err)
}
if err := keyBytes.Validate(); err != nil {
panic(err)
}
dn := pkix.Name{
Country: []string{"EN"},
Organization: []string{"org"},
OrganizationalUnit: []string{"org"},
Locality: []string{"city"},
Province: []string{"province"},
CommonName: "name",
}
asn1Dn, err := asn1.Marshal(dn)
if err != nil {
panic(err)
}
template := x509.CertificateRequest{
Raw: asn1Dn,
SignatureAlgorithm: x509.SHA256WithRSA,
}
csrBytes, err := x509.CreateCertificateRequest(rand.Reader, &template, keyBytes)
// how to do with csrBytes next?
}
Finally I resolved the problem by myself. Now I should write the answer for others face the same issue.
The solution is using software.sslmate.com/src/go-pkcs12
which provides function Encode
to encode given bytes data created from x509.CreateCertificate
.
Look at the example codes below:
func main() {
keyBytes, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
panic(err)
}
if err := keyBytes.Validate(); err != nil {
panic(err)
}
template := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Country: []string{"EN"},
Organization: []string{"org"},
OrganizationalUnit: []string{"org"},
Locality: []string{"city"},
Province: []string{"province"},
CommonName: "name",
},
}
derBytes, err := x509.CreateCertificate(rand.Reader, template, template, &keyBytes.PublicKey, keyBytes)
if err != nil {
panic(err)
}
cert, err := x509.ParseCertificate(derBytes)
if err != nil {
panic(err)
}
pfxBytes, err := pkcs12.Encode(rand.Reader, keyBytes, cert, []*x509.Certificate{}, pkcs12.DefaultPassword)
if err != nil {
panic(err)
}
// see if pfxBytes valid
_, _, _, err = pkcs12.DecodeChain(pfxBytes, pkcs12.DefaultPassword)
if err != nil {
panic(err)
}
if err := ioutil.WriteFile(
"/path/to/pri.pfx",
pfxBytes,
os.ModePerm,
); err != nil {
panic(err)
}
}
Everyone can find the source code in my github repo yuchanns/gobyexample
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.