1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| import ( "crypto/rand" "crypto/rsa" "crypto/x509" "crypto/x509/pkix" "io/ioutil" "log" "math/big" "time" )
func main() { ca := &x509.Certificate{ SerialNumber: big.NewInt(1653), Subject: pkix.Name{ Country: []string{"China"}, Organization: []string{""}, OrganizationalUnit: []string{""}, }, NotBefore: time.Now(), NotAfter: time.Now().AddDate(10, 0, 0), SubjectKeyId: []byte{1, 2, 3, 4, 5}, BasicConstraintsValid: true, IsCA: true, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, } caSelfSignedPrivateKey, _ := rsa.GenerateKey(rand.Reader, 1024) caSelfSignedPublicKey := &caSelfSignedPrivateKey.PublicKey caSelfSigned, err := x509.CreateCertificate(rand.Reader, ca, ca, caSelfSignedPublicKey, caSelfSignedPrivateKey) if err != nil { log.Println("create ca failed", err) return } caSelfSignedFile := "ca.pem" log.Println("write to", caSelfSignedFile) ioutil.WriteFile(caSelfSignedFile, caSelfSigned, 0777)
caSelfSignedPrivateKeyFile := "ca.key" caSelfSignedPrivateKeyDER := x509.MarshalPKCS1PrivateKey(caSelfSignedPrivateKey) log.Println("write to", caSelfSignedPrivateKeyFile) ioutil.WriteFile(caSelfSignedPrivateKeyFile, caSelfSignedPrivateKeyDER, 0777)
cert := &x509.Certificate{ SerialNumber: big.NewInt(1658), Subject: pkix.Name{ Country: []string{"China"}, Organization: []string{""}, OrganizationalUnit: []string{""}, }, NotBefore: time.Now(), NotAfter: time.Now().AddDate(10, 0, 0), SubjectKeyId: []byte{1, 2, 3, 4, 6}, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, } certPrivateKey, _ := rsa.GenerateKey(rand.Reader, 1024) certPublicKey := &certPrivateKey.PublicKey
certSigned, err2 := x509.CreateCertificate(rand.Reader, cert, ca, certPublicKey, caSelfSignedPrivateKey) if err != nil { log.Println("create cert2 failed", err2) return }
certFile := "cert.pem" log.Println("write to", certFile) ioutil.WriteFile(certFile, certSigned, 0777)
certPrivateKeyFile := "cert.key" certPrivateKeyDER := x509.MarshalPKCS1PrivateKey(certPrivateKey) log.Println("write to", certPrivateKeyFile) ioutil.WriteFile(certPrivateKeyFile, certPrivateKeyDER, 0777)
ca_tr, _ := x509.ParseCertificate(caSelfSigned) cert_tr, _ := x509.ParseCertificate(certSigned) err = cert_tr.CheckSignatureFrom(ca_tr) log.Println("check signature", err) }
|