在 golang 中创建密钥和证书,与 openssl 为本地主机所做的操作相同
时间:2024-04-09
浏览:392
作者:佚名
知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《在 golang 中创建密钥和证书,与 openssl 为本地主机所做的操作相同》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!
问题内容
如何在 go 中编写与以下 openssl 命令等效的代码?
openssl req -subj /C=/ST=/O=/L=/CN=localhost/OU=/ -x509 -nodes -days 3650 \
-newkey rsa:4096 -keyout test.key -out test.crt
目标是根据其证书请求生成新证书。
正确答案
通过这种方式找到了我的解决方案-
key, err := rsa.generatekey(rand.reader, 4096)
if err != nil {
return "", "", err
}
keybytes := x509.marshalpkcs1privatekey(key)
// pem encoding of private key
keypem := pem.encodetomemory(
&pem.block{
type: "rsa private key",
bytes: keybytes,
},
)
fmt.println(string(keypem))
notbefore := time.now()
notafter := notbefore.add(365*24*10*time.hour)
//create certificate templet
template := x509.certificate{
serialnumber: big.newint(0),
subject: pkix.name{commonname: "localhost"},
signaturealgorithm: x509.sha256withrsa,
notbefore: notbefore,
notafter: notafter,
basicconstraintsvalid: true,
keyusage: x509.keyusagedigitalsignature | x509.keyusagekeyagreement | x509.keyusagekeyencipherment | x509.keyusagedataencipherment,
extkeyusage: []x509.extkeyusage{x509.extkeyusageserverauth, x509.extkeyusageclientauth},
}
//create certificate using templet
derbytes, err := x509.createcertificate(rand.reader, &template, &template, &key.publickey, key)
if err != nil {
return "", "", err
}
//pem encoding of certificate
certpem := string(pem.encodetomemory(
&pem.block{
type: "certificate",
bytes: derbytes,
},
))
fmt.println(certpem))您可以考虑使用 cloudflare/cfssl(其中包含 cfssl.initca 包)作为 shown here:
var req *csr.CertificateRequest
hostname := "cloudflare.com"
crl := "http://crl.cloudflare.com/655c6a9b-01c6-4eea-bf21-be690cc315e0.crl" //cert_uuid.crl
for _, param := range validKeyParams {
for _, caconfig := range validCAConfigs {
req = &csr.CertificateRequest{
Names: []csr.Name{
{
C: "US",
ST: "California",
L: "San Francisco",
O: "CloudFlare",
OU: "Systems Engineering",
},
},
CN: hostname,
Hosts: []string{hostname, "www." + hostname},
KeyRequest: ¶m,
CA: &caconfig,
CRL: crl,
}
certBytes, _, keyBytes, err := New(req)
if err != nil {
t.Fatal("InitCA failed:", err)
}
理论要掌握,实操不能落!以上关于《在 golang 中创建密钥和证书,与 openssl 为本地主机所做的操作相同》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
