How to use makeSubject method of x509 Package

Best K6 code snippet using x509.makeSubject

tls.go

Source:tls.go Github

copy

Full Screen

1package tlsutils2import (3 "bytes"4 "crypto/ecdsa"5 "crypto/ed25519"6 "crypto/elliptic"7 "crypto/rand"8 "crypto/rsa"9 "crypto/tls"10 "crypto/x509"11 "crypto/x509/pkix"12 "encoding/pem"13 "errors"14 "fmt"15 "math/big"16 "net"17 "strings"18 "time"19 "github.com/dgrijalva/jwt-go"20)21func MakeSubject() pkix.Name {22 return pkix.Name{23 Organization: []string{"Acme, Inc"},24 Locality: []string{"Nowhere"},25 Province: []string{"USA"},26 StreetAddress: []string{"18 main street"},27 PostalCode: []string{"014611"},28 }29}30// params for creating a tls cert31type TlsParams struct {32 // Comma-separated hostnames and IPs to generate a certificate for33 Host string34 // Creation date formatted as Jan 1 15:04:05 201135 ValidFrom time.Time36 // Duration that certificate is valid for37 ValidFor time.Duration38 // whether this cert should be its own Certificate Authority39 IsCa bool40 // Size of RSA key to generate. Ignored if EcdsaCurve is set41 RsaBits int42 // ECDSA curve to use to generate a key. Valid values are P224, P256 (recommended), P384, P52143 EcdsaCurve string44 // Generate an Ed25519 key45 Ed25519 bool46}47// copy a tls params struct48func (t *TlsParams) Copy() TlsParams {49 return TlsParams{50 Host: t.Host,51 ValidFrom: t.ValidFrom,52 ValidFor: t.ValidFor,53 IsCa: t.IsCa,54 RsaBits: t.RsaBits,55 EcdsaCurve: t.EcdsaCurve,56 Ed25519: t.Ed25519,57 }58}59var (60 Day = time.Hour * 2461 Week = Day * 762 Month = Week * 463 Year = Month * 1264)65// default params for creating a tls cert66// a function for immutability67func DefaultTlsParams() TlsParams {68 return TlsParams{69 Host: "localhost",70 ValidFrom: time.Now(),71 ValidFor: Year,72 IsCa: false,73 RsaBits: 2048,74 EcdsaCurve: "",75 Ed25519: false,76 }77}78// params returned by certificate generator79type TlsCert struct {80 CertType string81 // certificate.pem (public key)82 PublicKey string83 // key.pem (private key)84 PrivateKey string85 // Certificate86 Certificate *x509.Certificate87 // private key88 Key interface{}89 // parameters (90 Params TlsParams91}92// generate a dca certificate from a rootc93func (t TlsCert) MakeDca() (TlsCert, error) {94 if !t.Certificate.IsCA {95 return TlsCert{}, fmt.Errorf("certificate must be a root certificate to issue a dca")96 }97 priv, err := generatePrivateKey(t.Params)98 if err != nil {99 return TlsCert{}, err100 }101 dcaTemplate := x509.Certificate{102 SerialNumber: generateSerialNumber(),103 Subject: MakeSubject(),104 NotBefore: t.Params.ValidFrom,105 NotAfter: t.Params.ValidFrom.Add(t.Params.ValidFor),106 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,107 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},108 BasicConstraintsValid: true,109 IsCA: true,110 MaxPathLenZero: false,111 MaxPathLen: 1,112 }113 AddHostToTemplate(t.Params.Host, &dcaTemplate)114 generatedCert, err := genTlsCert(t.Params, &dcaTemplate, t.Certificate, publicKey(priv), t.Key)115 if err != nil {116 return TlsCert{}, err117 }118 generatedCert.Key = priv119 return generatedCert, nil120}121// generate a dca certificate from a rootc122func (t TlsCert) MakeServerCertificate() (TlsCert, error) {123 if !t.Certificate.IsCA {124 return TlsCert{}, fmt.Errorf("certificate must be a root certificate to issue a dca")125 }126 serialNumber := generateSerialNumber()127 priv, err := generatePrivateKey(t.Params)128 if err != nil {129 return TlsCert{}, err130 }131 serverTemplate := x509.Certificate{132 SerialNumber: serialNumber,133 NotBefore: t.Params.ValidFrom,134 NotAfter: t.Params.ValidFrom.Add(t.Params.ValidFor),135 KeyUsage: x509.KeyUsageCRLSign,136 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},137 IsCA: false,138 MaxPathLenZero: true,139 }140 AddHostToTemplate(t.Params.Host, &serverTemplate)141 generatedCert, err := genTlsCert(t.Params, &serverTemplate, t.Certificate, publicKey(priv), t.Key)142 if err != nil {143 return TlsCert{}, err144 }145 generatedCert.Key = priv146 return generatedCert, nil147}148// generate a private key of a given type specified in params149func generatePrivateKey(params TlsParams) (priv interface{}, err error) {150 switch params.EcdsaCurve {151 case "":152 if params.Ed25519 {153 _, priv, err = ed25519.GenerateKey(rand.Reader)154 } else {155 priv, err = rsa.GenerateKey(rand.Reader, params.RsaBits)156 }157 case P224:158 priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)159 case P256:160 priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)161 case P384:162 priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)163 case P521:164 priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)165 default:166 return priv, fmt.Errorf("unrecognized elliptic curve: %q", params.EcdsaCurve)167 }168 if err != nil {169 return priv, fmt.Errorf("failed to generate private key: %v", err)170 }171 return priv, nil172}173// generate a tls cert from params174func genTlsCert(params TlsParams, template, parent *x509.Certificate, publicKey interface{}, privateKey interface{}) (cert TlsCert, err error) {175 derBytes, err := x509.CreateCertificate(rand.Reader, template, parent, publicKey, privateKey)176 if err != nil {177 return TlsCert{}, fmt.Errorf("failed to create certificate: %v", err)178 }179 certOut := bytes.NewBufferString("")180 if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {181 return TlsCert{}, fmt.Errorf("failed to write data to cert.pem: %v", err)182 }183 xCert, err := x509.ParseCertificate(derBytes)184 if err != nil {185 return TlsCert{}, err186 }187 keyOut := bytes.NewBufferString("")188 privBytes, err := x509.MarshalPKCS8PrivateKey(privateKey)189 if err != nil {190 return TlsCert{}, fmt.Errorf("unable to marshal private key: %v", err)191 }192 if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil {193 return TlsCert{}, fmt.Errorf("failed to write data to key.pem: %v", err)194 }195 return TlsCert{196 PublicKey: certOut.String(),197 PrivateKey: keyOut.String(),198 Certificate: xCert,199 Key: privateKey,200 Params: params,201 }, nil202}203// generate a serial number for use in certs204func generateSerialNumber() *big.Int {205 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)206 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)207 if err != nil {208 panic(fmt.Errorf("failed to generate serial number: %v", err))209 }210 return serialNumber211}212func AddHostToTemplate(host string, template *x509.Certificate) {213 hosts := strings.Split(host, ",")214 for _, h := range hosts {215 if ip := net.ParseIP(h); ip != nil {216 template.IPAddresses = append(template.IPAddresses, ip)217 } else {218 template.DNSNames = append(template.DNSNames, h)219 }220 }221}222func MakeCertificateDefault() (cert TlsCert, err error) {223 return MakeCertificate(DefaultTlsParams())224}225// create a public key from a private key226func publicKey(priv interface{}) interface{} {227 switch k := priv.(type) {228 case *rsa.PrivateKey:229 return &k.PublicKey230 case *ecdsa.PrivateKey:231 return &k.PublicKey232 case ed25519.PrivateKey:233 return k.Public().(ed25519.PublicKey)234 default:235 return nil236 }237}238// curve types for rsa keys239const (240 P224 = "P224"241 P256 = "P256"242 P384 = "P384"243 P521 = "P521"244)245// Create a tls certificate246// adapted from https://golang.org/src/crypto/tls/generate_cert.go247func MakeCertificate(params TlsParams) (cert TlsCert, err error) {248 if len(params.Host) == 0 {249 return cert, errors.New("missing required host parameter")250 }251 priv, err := generatePrivateKey(params)252 if err != nil {253 return TlsCert{}, err254 }255 // ECDSA, ED25519 and RSA subject keys should have the DigitalSignature256 // KeyUsage bits set in the x509.Certificate template257 keyUsage := x509.KeyUsageDigitalSignature258 // Only RSA subject keys should have the KeyEncipherment KeyUsage bits set. In259 // the context of TLS this KeyUsage is particular to RSA key exchange and260 // authentication.261 if _, isRSA := priv.(*rsa.PrivateKey); isRSA {262 keyUsage |= x509.KeyUsageKeyEncipherment263 }264 template := x509.Certificate{265 SerialNumber: generateSerialNumber(),266 Subject: MakeSubject(),267 NotBefore: params.ValidFrom,268 NotAfter: params.ValidFrom.Add(params.ValidFor),269 KeyUsage: keyUsage,270 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},271 BasicConstraintsValid: true,272 }273 AddHostToTemplate(params.Host, &template)274 if params.IsCa {275 template.IsCA = true276 template.KeyUsage |= x509.KeyUsageCertSign277 template.KeyUsage |= x509.KeyUsageCRLSign278 template.MaxPathLen = 2279 template.Subject.CommonName = "Root CA"280 }281 return genTlsCert(params, &template, &template, publicKey(priv), priv)282}283// verify a tls key parir is valid284func VerifyCertificate(cert TlsCert) (isValid bool, err error) {285 _, err = tls.X509KeyPair([]byte(cert.PublicKey), []byte(cert.PrivateKey))286 return err == nil, err287}288func VerifyKeyPair(rsaPublicKey, rsaPrivateKey string) (isValid bool, err error) {289 key, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(rsaPrivateKey))290 if err != nil {291 return isValid, err292 }293 pubKey, err := jwt.ParseRSAPublicKeyFromPEM([]byte(rsaPublicKey))294 if err != nil {295 return isValid, err296 }297 return key.PublicKey.Equal(pubKey), err298}...

Full Screen

Full Screen

crypto.go

Source:crypto.go Github

copy

Full Screen

...56 }57 // Create CA cert58 caCert := x509.Certificate{59 SerialNumber: caSerial,60 Subject: makeSubject(caCertName),61 NotBefore: notBefore,62 NotAfter: notAfter,63 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,64 IsCA: true,65 SubjectKeyId: caKeyId,66 BasicConstraintsValid: true,67 }68 derBytes, err := x509.CreateCertificate(rand.Reader, &caCert, &caCert, &caKey.PublicKey, caKey)69 if err != nil {70 return nil, err71 }72 certInfo.CACert = certToBase64String(derBytes)73 // Create HTTPS server key74 serverKey, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)75 if err != nil {76 return nil, err77 }78 serverKeyBase64, err := keyToBase64String(serverKey)79 if err != nil {80 return nil, err81 }82 certInfo.ServerKey = serverKeyBase6483 serverSerial, err := makeSerial()84 if err != nil {85 return nil, err86 }87 serverKeyId, err := bigIntHash(serverKey.D)88 if err != nil {89 return nil, err90 }91 // Create HTTPS server cert92 serverCert := x509.Certificate{93 SerialNumber: serverSerial,94 Subject: makeSubject(serverCertName),95 NotBefore: notBefore,96 NotAfter: notAfter,97 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},98 AuthorityKeyId: caCert.SubjectKeyId,99 SubjectKeyId: serverKeyId,100 DNSNames: []string{serverCertName},101 }102 derBytes, err = x509.CreateCertificate(rand.Reader, &serverCert, &caCert, &serverKey.PublicKey, caKey)103 if err != nil {104 return nil, err105 }106 certInfo.ServerCert = certToBase64String(derBytes)107 // Create HTTPS client key108 clientKey, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)109 if err != nil {110 return nil, err111 }112 clientKeyBase64, err := keyToBase64String(clientKey)113 if err != nil {114 return nil, err115 }116 certInfo.ClientKey = clientKeyBase64117 clientSerial, err := makeSerial()118 if err != nil {119 return nil, err120 }121 clientKeyId, err := bigIntHash(clientKey.D)122 if err != nil {123 return nil, err124 }125 // Create HTTPS client cert126 clientCert := x509.Certificate{127 SerialNumber: clientSerial,128 Subject: makeSubject(clientCertName),129 NotBefore: notBefore,130 NotAfter: notAfter,131 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},132 AuthorityKeyId: caCert.SubjectKeyId,133 SubjectKeyId: clientKeyId,134 }135 derBytes, err = x509.CreateCertificate(rand.Reader, &clientCert, &caCert, &clientKey.PublicKey, caKey)136 if err != nil {137 return nil, err138 }139 certInfo.ClientCert = certToBase64String(derBytes)140 return certInfo, nil141}142func makeSubject(cn string) pkix.Name {143 return pkix.Name{144 Country: []string{"US"},145 Locality: []string{"RTP"},146 Organization: []string{"NetApp"},147 Province: []string{"NC"},148 CommonName: cn,149 }150}151func makeSerial() (*big.Int, error) {152 maxSerial := big.NewInt(math.MaxInt64)153 serial, err := rand.Int(rand.Reader, maxSerial)154 if nil != err {155 return nil, err156 }...

Full Screen

Full Screen

x509.go

Source:x509.go Github

copy

Full Screen

...113 parsed, err := parseCertificate(encoded)114 if err != nil {115 throw(ctx, err)116 }117 return makeSubject(parsed.Subject)118}119func parseCertificate(encoded []byte) (*x509.Certificate, error) {120 decoded, _ := pem.Decode(encoded)121 if decoded == nil {122 err := errors.New("failed to decode certificate PEM file")123 return nil, err124 }125 parsed, err := x509.ParseCertificate(decoded.Bytes)126 if err != nil {127 err = errors.Wrap(err, "failed to parse certificate")128 return nil, err129 }130 return parsed, nil131}132func makeCertificate(parsed *x509.Certificate) (Certificate, error) {133 publicKey, err := makePublicKey(parsed.PublicKey)134 if err != nil {135 return Certificate{}, err136 }137 return Certificate{138 Subject: makeSubject(parsed.Subject),139 Issuer: makeIssuer(parsed.Issuer),140 NotBefore: iso8601(parsed.NotBefore),141 NotAfter: iso8601(parsed.NotAfter),142 AltNames: altNames(parsed),143 SignatureAlgorithm: signatureAlgorithm(parsed.SignatureAlgorithm),144 FingerPrint: fingerPrint(parsed),145 PublicKey: publicKey,146 }, nil147}148func makeSubject(subject pkix.Name) Subject {149 return Subject{150 CommonName: subject.CommonName,151 Country: first(subject.Country),152 PostalCode: first(subject.PostalCode),153 StateOrProvinceName: first(subject.Province),154 LocalityName: first(subject.Locality),155 StreetAddress: first(subject.StreetAddress),156 OrganizationName: first(subject.Organization),157 OrganizationalUnitName: subject.OrganizationalUnit,158 Names: makeRdns(subject.Names),159 }160}161func makeIssuer(issuer pkix.Name) Issuer {162 return Issuer{...

Full Screen

Full Screen

makeSubject

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cert := x509.Certificate{}4 cert.Subject.Country = []string{"US"}5 cert.Subject.Province = []string{"California"}6 cert.Subject.Locality = []string{"San Francisco"}7 cert.Subject.Organization = []string{"Example Inc"}8 cert.Subject.OrganizationalUnit = []string{"Example Inc. IT Department"}9 cert.Subject.PostalCode = []string{"94040"}10 cert.Subject.StreetAddress = []string{"123 Main Street"}11 cert.Subject.ExtraNames = []pkix.AttributeTypeAndValue{12 pkix.AttributeTypeAndValue{13 Type: pkix.ObjectIdentifier{2, 5, 4, 17},14 },15 }16 cert.Subject.Names = []pkix.AttributeTypeAndValue{17 pkix.AttributeTypeAndValue{18 Type: pkix.ObjectIdentifier{2, 5, 4, 4},19 },20 }21 cert.Subject.ExtraNames = []pkix.AttributeTypeAndValue{22 pkix.AttributeTypeAndValue{23 Type: pkix.ObjectIdentifier{2, 5, 4, 42},24 },25 }26 cert.Subject.Names = []pkix.AttributeTypeAndValue{27 pkix.AttributeTypeAndValue{28 Type: pkix.ObjectIdentifier{2, 5, 4, 3},29 },30 }31 cert.Subject.ExtraNames = []pkix.AttributeTypeAndValue{32 pkix.AttributeTypeAndValue{33 Type: pkix.ObjectIdentifier{2, 5, 4, 5},34 },35 }36 cert.Subject.Names = []pkix.AttributeTypeAndValue{37 pkix.AttributeTypeAndValue{38 Type: pkix.ObjectIdentifier{2, 5, 4, 6},39 },40 }41 cert.Subject.ExtraNames = []pkix.AttributeTypeAndValue{42 pkix.AttributeTypeAndValue{43 Type: pkix.ObjectIdentifier{2, 5, 4, 7},

Full Screen

Full Screen

makeSubject

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cert, _ := ioutil.ReadFile("cert.pem")4 block, _ := pem.Decode(cert)5 certObj, _ := x509.ParseCertificate(block.Bytes)6 fmt.Println(certObj.Subject)7}

Full Screen

Full Screen

makeSubject

Using AI Code Generation

copy

Full Screen

1import "crypto/x509"2func main() {3 x509.MakeSubject()4}5import "crypto/x509"6func main() {7 x509.MakeSubject()8}9./1.go:6: x509.MakeSubject undefined (type *x509.Certificate has no field or method MakeSubject)10./2.go:6: x509.MakeSubject undefined (type *x509.Certificate has no field or method MakeSubject)11type Certificate struct {12}13func (c *Certificate) makeSubject() {14}

Full Screen

Full Screen

makeSubject

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 x509Subject := x509.Name{}4 x509Subject.Country = []string{"Country"}5 x509Subject.Locality = []string{"Locality"}6 x509Subject.Organization = []string{"Organization"}7 x509Subject.OrganizationalUnit = []string{"OrganizationalUnit"}8 x509Subject.Province = []string{"Province"}9 x509Subject.StreetAddress = []string{"StreetAddress"}10 x509Subject.PostalCode = []string{"PostalCode"}11 x509Subject.ExtraNames = []pkix.AttributeTypeAndValue{12 pkix.AttributeTypeAndValue{13 Type: []int{2, 5, 4, 3},14 },15 }16 fmt.Println(x509Subject)17}

Full Screen

Full Screen

makeSubject

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 subject := x509.Name{4 Country: []string{"US"},5 Organization: []string{"Acme Co"},6 OrganizationalUnit: []string{"IT"},7 Locality: []string{"San Francisco"},8 Province: []string{"CA"},9 StreetAddress: []string{"1234 Main St."},10 PostalCode: []string{"94111"},11 }12 subjectKeyID := []byte{1, 2, 3, 4, 5}13 subjectKeyId := x509.SubjectKeyId(subjectKeyID)14 subj := subject.ToRDNSequence()15 subjKeyId := subjectKeyId.ToRDNSequence()16 fmt.Println("Subject is", subj)17 fmt.Println("Subject Key ID is", subjKeyId)18}19Go | x509.SubjectKeyId.ToRDNSequence() method20Go | x509.SubjectKeyId.String() method21Go | x509.SubjectKeyId.Equal() method22Go | x509.SubjectKeyId.Bytes() method23Go | x509.SubjectKeyId.MarshalJSON() method24Go | x509.SubjectKeyId.MarshalText() method25Go | x509.SubjectKeyId.UnmarshalJSON() method26Go | x509.SubjectKeyId.UnmarshalText() method27Go | x509.SubjectKeyId.Set() method28Go | x509.SubjectKeyId.Copy() method29Go | x509.SubjectKeyId.Empty() method30Go | x509.SubjectKeyId.Size() method31Go | x509.SubjectKeyId.Free() method32Go | x509.SubjectKeyId.Duplicate() method33Go | x509.SubjectKeyId.Get() method

Full Screen

Full Screen

makeSubject

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cert := x509.Certificate{4 SerialNumber: big.NewInt(1658),5 Subject: pkix.Name{6 Organization: []string{"Acme Co"},7 },8 NotBefore: time.Now(),9 NotAfter: time.Now().Add(365 * 24 * time.Hour),10 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},11 }12 priv, _ := rsa.GenerateKey(rand.Reader, 2048)13 certBytes, _ := x509.CreateCertificate(rand.Reader, &cert, &cert, &priv.PublicKey, priv)14 certPool := x509.NewCertPool()15 certPool.AppendCertsFromPEM(certBytes)16 tlsCert := tls.Certificate{17 Certificate: [][]byte{certBytes},18 }19 config := &tls.Config{20 Certificates: []tls.Certificate{tlsCert},21 }22 listener, _ := tls.Listen("tcp", "

Full Screen

Full Screen

makeSubject

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var (4 cert, err = x509.ParseCertificate([]byte("certificate data"))5 if err != nil {6 fmt.Println(err)7 }8 subjectStr = subject.String()9 fmt.Println(s

Full Screen

Full Screen

makeSubject

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 priv, err := rsa.GenerateKey(rand.Reader, 2048)4 if err != nil {5 log.Fatal(err)6 }7 subject := makeSubject()8 cert, err := x509.CreateCertificate(rand.Reader, subject, subject, &priv.PublicKey, priv)9 if err != nil {10 log.Fatal(err)11 }12 pem.Encode(os.Stdout, &pem.Block{Type: "CERTIFICATE", Bytes: cert})13}14func makeSubject() *x509.Certificate {15 return &x509.Certificate{16 SerialNumber: big.NewInt(1),17 Subject: pkix.Name{18 Organization: []string{"myorg"},19 Country: []string{"US"},20 },21 NotBefore: time.Now(),22 NotAfter: time.Now().AddDate(1, 0, 0),23 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},24 }25}26 Version: 3 (0x2)27 RSA Public-Key: (2048 bit)

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful