How to use uris method of x509 Package

Best K6 code snippet using x509.uris

csr.go

Source:csr.go Github

copy

Full Screen

...40 }41 return ipAddresses42}43func URIsForCertificate(crt *v1.Certificate) ([]*url.URL, error) {44 uris, err := URLsFromStrings(crt.Spec.URIs)45 if err != nil {46 return nil, fmt.Errorf("failed to parse URIs: %s", err)47 }48 return uris, nil49}50func DNSNamesForCertificate(crt *v1.Certificate) ([]string, error) {51 _, err := URLsFromStrings(crt.Spec.DNSNames)52 if err != nil {53 return nil, fmt.Errorf("failed to parse DNSNames: %s", err)54 }55 return crt.Spec.DNSNames, nil56}57func URLsFromStrings(urlStrs []string) ([]*url.URL, error) {58 var urls []*url.URL59 var errs []string60 for _, urlStr := range urlStrs {61 url, err := url.Parse(urlStr)62 if err != nil {63 errs = append(errs, err.Error())64 continue65 }66 urls = append(urls, url)67 }68 if len(errs) > 0 {69 return nil, errors.New(strings.Join(errs, ", "))70 }71 return urls, nil72}73func IPAddressesToString(ipAddresses []net.IP) []string {74 var ipNames []string75 for _, ip := range ipAddresses {76 ipNames = append(ipNames, ip.String())77 }78 return ipNames79}80func URLsToString(uris []*url.URL) []string {81 var uriStrs []string82 for _, uri := range uris {83 if uri == nil {84 panic("provided uri to string is nil")85 }86 uriStrs = append(uriStrs, uri.String())87 }88 return uriStrs89}90func removeDuplicates(in []string) []string {91 var found []string92Outer:93 for _, i := range in {94 for _, i2 := range found {95 if i2 == i {96 continue Outer97 }98 }99 found = append(found, i)100 }101 return found102}103// OrganizationForCertificate will return the Organization to set for the104// Certificate resource.105// If an Organization is not specifically set, a default will be used.106func OrganizationForCertificate(crt *v1.Certificate) []string {107 if crt.Spec.Subject == nil {108 return nil109 }110 return crt.Spec.Subject.Organizations111}112// SubjectForCertificate will return the Subject from the Certificate resource or an empty one if it is not set113func SubjectForCertificate(crt *v1.Certificate) v1.X509Subject {114 if crt.Spec.Subject == nil {115 return v1.X509Subject{}116 }117 return *crt.Spec.Subject118}119var serialNumberLimit = new(big.Int).Lsh(big.NewInt(1), 128)120func BuildKeyUsages(usages []v1.KeyUsage, isCA bool) (ku x509.KeyUsage, eku []x509.ExtKeyUsage, err error) {121 var unk []v1.KeyUsage122 if isCA {123 ku |= x509.KeyUsageCertSign124 }125 if len(usages) == 0 {126 usages = append(usages, v1.DefaultKeyUsages()...)127 }128 for _, u := range usages {129 if kuse, ok := apiutil.KeyUsageType(u); ok {130 ku |= kuse131 } else if ekuse, ok := apiutil.ExtKeyUsageType(u); ok {132 eku = append(eku, ekuse)133 } else {134 unk = append(unk, u)135 }136 }137 if len(unk) > 0 {138 err = fmt.Errorf("unknown key usages: %v", unk)139 }140 return141}142func BuildCertManagerKeyUsages(ku x509.KeyUsage, eku []x509.ExtKeyUsage) []v1.KeyUsage {143 usages := apiutil.KeyUsageStrings(ku)144 usages = append(usages, apiutil.ExtKeyUsageStrings(eku)...)145 return usages146}147// GenerateCSR will generate a new *x509.CertificateRequest template to be used148// by issuers that utilise CSRs to obtain Certificates.149// The CSR will not be signed, and should be passed to either EncodeCSR or150// to the x509.CreateCertificateRequest function.151func GenerateCSR(crt *v1.Certificate) (*x509.CertificateRequest, error) {152 commonName := crt.Spec.CommonName153 iPAddresses := IPAddressesForCertificate(crt)154 organization := OrganizationForCertificate(crt)155 subject := SubjectForCertificate(crt)156 dnsNames, err := DNSNamesForCertificate(crt)157 if err != nil {158 return nil, err159 }160 uriNames, err := URIsForCertificate(crt)161 if err != nil {162 return nil, err163 }164 if len(commonName) == 0 && len(dnsNames) == 0 && len(uriNames) == 0 && len(crt.Spec.EmailAddresses) == 0 && len(crt.Spec.IPAddresses) == 0 {165 return nil, fmt.Errorf("no common name, DNS name, URI SAN, or Email SAN specified on certificate")166 }167 pubKeyAlgo, sigAlgo, err := SignatureAlgorithm(crt)168 if err != nil {169 return nil, err170 }171 var extraExtensions []pkix.Extension172 if crt.Spec.EncodeUsagesInRequest == nil || *crt.Spec.EncodeUsagesInRequest {173 extraExtensions, err = buildKeyUsagesExtensionsForCertificate(crt)174 if err != nil {175 return nil, err176 }177 }178 return &x509.CertificateRequest{179 // Version 0 is the only one defined in the PKCS#10 standard, RFC2986.180 // This value isn't used by Go at the time of writing.181 // https://datatracker.ietf.org/doc/html/rfc2986#section-4182 Version: 0,183 SignatureAlgorithm: sigAlgo,184 PublicKeyAlgorithm: pubKeyAlgo,185 Subject: pkix.Name{186 Country: subject.Countries,187 Organization: organization,188 OrganizationalUnit: subject.OrganizationalUnits,189 Locality: subject.Localities,190 Province: subject.Provinces,191 StreetAddress: subject.StreetAddresses,192 PostalCode: subject.PostalCodes,193 SerialNumber: subject.SerialNumber,194 CommonName: commonName,195 },196 DNSNames: dnsNames,197 IPAddresses: iPAddresses,198 URIs: uriNames,199 EmailAddresses: crt.Spec.EmailAddresses,200 ExtraExtensions: extraExtensions,201 }, nil202}203func buildKeyUsagesExtensionsForCertificate(crt *v1.Certificate) ([]pkix.Extension, error) {204 ku, ekus, err := BuildKeyUsages(crt.Spec.Usages, crt.Spec.IsCA)205 if err != nil {206 return nil, fmt.Errorf("failed to build key usages: %w", err)207 }208 usage, err := buildASN1KeyUsageRequest(ku)209 if err != nil {210 return nil, fmt.Errorf("failed to asn1 encode usages: %w", err)211 }212 asn1ExtendedUsages := []asn1.ObjectIdentifier{}213 for _, eku := range ekus {214 if oid, ok := OIDFromExtKeyUsage(eku); ok {215 asn1ExtendedUsages = append(asn1ExtendedUsages, oid)216 }217 }218 extraExtensions := []pkix.Extension{usage}219 if len(ekus) > 0 {220 extendedUsage := pkix.Extension{221 Id: OIDExtensionExtendedKeyUsage,222 }223 extendedUsage.Value, err = asn1.Marshal(asn1ExtendedUsages)224 if err != nil {225 return nil, fmt.Errorf("failed to asn1 encode extended usages: %w", err)226 }227 extraExtensions = append(extraExtensions, extendedUsage)228 }229 return extraExtensions, nil230}231// GenerateTemplate will create a x509.Certificate for the given Certificate resource.232// This should create a Certificate template that is equivalent to the CertificateRequest233// generated by GenerateCSR.234// The PublicKey field must be populated by the caller.235func GenerateTemplate(crt *v1.Certificate) (*x509.Certificate, error) {236 commonName := crt.Spec.CommonName237 dnsNames := crt.Spec.DNSNames238 ipAddresses := IPAddressesForCertificate(crt)239 organization := OrganizationForCertificate(crt)240 subject := SubjectForCertificate(crt)241 uris, err := URLsFromStrings(crt.Spec.URIs)242 if err != nil {243 return nil, err244 }245 keyUsages, extKeyUsages, err := BuildKeyUsages(crt.Spec.Usages, crt.Spec.IsCA)246 if err != nil {247 return nil, err248 }249 if len(commonName) == 0 && len(dnsNames) == 0 && len(ipAddresses) == 0 && len(uris) == 0 && len(crt.Spec.EmailAddresses) == 0 {250 return nil, fmt.Errorf("no common name or subject alt names requested on certificate")251 }252 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)253 if err != nil {254 return nil, fmt.Errorf("failed to generate serial number: %s", err.Error())255 }256 certDuration := apiutil.DefaultCertDuration(crt.Spec.Duration)257 pubKeyAlgo, _, err := SignatureAlgorithm(crt)258 if err != nil {259 return nil, err260 }261 return &x509.Certificate{262 // Version must be 2 according to RFC5280.263 // A version value of 2 confusingly means version 3.264 // This value isn't used by Go at the time of writing.265 // https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.1266 Version: 2,267 BasicConstraintsValid: true,268 SerialNumber: serialNumber,269 PublicKeyAlgorithm: pubKeyAlgo,270 IsCA: crt.Spec.IsCA,271 Subject: pkix.Name{272 Country: subject.Countries,273 Organization: organization,274 OrganizationalUnit: subject.OrganizationalUnits,275 Locality: subject.Localities,276 Province: subject.Provinces,277 StreetAddress: subject.StreetAddresses,278 PostalCode: subject.PostalCodes,279 SerialNumber: subject.SerialNumber,280 CommonName: commonName,281 },282 NotBefore: time.Now(),283 NotAfter: time.Now().Add(certDuration),284 // see http://golang.org/pkg/crypto/x509/#KeyUsage285 KeyUsage: keyUsages,286 ExtKeyUsage: extKeyUsages,287 DNSNames: dnsNames,288 IPAddresses: ipAddresses,289 URIs: uris,290 EmailAddresses: crt.Spec.EmailAddresses,291 }, nil292}293// GenerateTemplate will create a x509.Certificate for the given294// CertificateRequest resource295func GenerateTemplateFromCertificateRequest(cr *v1.CertificateRequest) (*x509.Certificate, error) {296 certDuration := apiutil.DefaultCertDuration(cr.Spec.Duration)297 keyUsage, extKeyUsage, err := BuildKeyUsages(cr.Spec.Usages, cr.Spec.IsCA)298 if err != nil {299 return nil, err300 }301 return GenerateTemplateFromCSRPEMWithUsages(cr.Spec.Request, certDuration, cr.Spec.IsCA, keyUsage, extKeyUsage)302}303func GenerateTemplateFromCSRPEM(csrPEM []byte, duration time.Duration, isCA bool) (*x509.Certificate, error) {...

Full Screen

Full Screen

certificate_request.go

Source:certificate_request.go Github

copy

Full Screen

...19 Subject Subject `json:"subject"`20 DNSNames MultiString `json:"dnsNames"`21 EmailAddresses MultiString `json:"emailAddresses"`22 IPAddresses MultiIP `json:"ipAddresses"`23 URIs MultiURL `json:"uris"`24 SANs []SubjectAlternativeName `json:"sans"`25 Extensions []Extension `json:"extensions"`26 SignatureAlgorithm SignatureAlgorithm `json:"signatureAlgorithm"`27 PublicKey interface{} `json:"-"`28 PublicKeyAlgorithm x509.PublicKeyAlgorithm `json:"-"`29 Signature []byte `json:"-"`30 Signer crypto.Signer `json:"-"`31}32// NewCertificateRequest creates a certificate request from a template.33func NewCertificateRequest(signer crypto.Signer, opts ...Option) (*CertificateRequest, error) {34 pub := signer.Public()35 o, err := new(Options).apply(&x509.CertificateRequest{36 PublicKey: pub,37 }, opts)38 if err != nil {39 return nil, err40 }41 // If no template use only the certificate request with the default leaf key42 // usages.43 if o.CertBuffer == nil {44 return &CertificateRequest{45 PublicKey: pub,46 Signer: signer,47 }, nil48 }49 // With templates50 var cr CertificateRequest51 if err := json.NewDecoder(o.CertBuffer).Decode(&cr); err != nil {52 return nil, errors.Wrap(err, "error unmarshaling certificate")53 }54 cr.PublicKey = pub55 cr.Signer = signer56 return &cr, nil57}58// newCertificateRequest is an internal method that creates a CertificateRequest59// from an x509.CertificateRequest.60//61// This method is used to create the template variable .Insecure.CR or to62// initialize the Certificate when no templates are used. newCertificateRequest63// will always ignore the SignatureAlgorithm because we cannot guarantee that64// the signer will be able to sign a certificate template if65// Certificate.SignatureAlgorithm is set.66func newCertificateRequest(cr *x509.CertificateRequest) *CertificateRequest {67 // Set SubjectAltName extension as critical if Subject is empty.68 fixSubjectAltName(cr)69 return &CertificateRequest{70 Version: cr.Version,71 Subject: newSubject(cr.Subject),72 DNSNames: cr.DNSNames,73 EmailAddresses: cr.EmailAddresses,74 IPAddresses: cr.IPAddresses,75 URIs: cr.URIs,76 Extensions: newExtensions(cr.Extensions),77 PublicKey: cr.PublicKey,78 PublicKeyAlgorithm: cr.PublicKeyAlgorithm,79 Signature: cr.Signature,80 // Do not enforce signature algorithm from the CSR, it might not81 // be compatible with the certificate signer.82 SignatureAlgorithm: 0,83 }84}85// GetCertificateRequest returns the equivalent x509.CertificateRequest.86func (c *CertificateRequest) GetCertificateRequest() (*x509.CertificateRequest, error) {87 cert := c.GetCertificate().GetCertificate()88 asn1Data, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{89 Subject: cert.Subject,90 DNSNames: cert.DNSNames,91 IPAddresses: cert.IPAddresses,92 EmailAddresses: cert.EmailAddresses,93 URIs: cert.URIs,94 ExtraExtensions: cert.ExtraExtensions,95 SignatureAlgorithm: x509.SignatureAlgorithm(c.SignatureAlgorithm),96 }, c.Signer)97 if err != nil {98 return nil, errors.Wrap(err, "error creating certificate request")99 }100 // This should not fail101 return x509.ParseCertificateRequest(asn1Data)102}103// GetCertificate returns the Certificate representation of the104// CertificateRequest.105//106// GetCertificate will not specify a SignatureAlgorithm, it's not possible to107// guarantee that the certificate signer can sign with the CertificateRequest108// SignatureAlgorithm.109func (c *CertificateRequest) GetCertificate() *Certificate {110 return &Certificate{111 Subject: c.Subject,112 DNSNames: c.DNSNames,113 EmailAddresses: c.EmailAddresses,114 IPAddresses: c.IPAddresses,115 URIs: c.URIs,116 SANs: c.SANs,117 Extensions: c.Extensions,118 PublicKey: c.PublicKey,119 PublicKeyAlgorithm: c.PublicKeyAlgorithm,120 SignatureAlgorithm: 0,121 }122}123// GetLeafCertificate returns the Certificate representation of the124// CertificateRequest, including KeyUsage and ExtKeyUsage extensions.125//126// GetLeafCertificate will not specify a SignatureAlgorithm, it's not possible127// to guarantee that the certificate signer can sign with the CertificateRequest128// SignatureAlgorithm.129func (c *CertificateRequest) GetLeafCertificate() *Certificate {130 keyUsage := x509.KeyUsageDigitalSignature131 if _, ok := c.PublicKey.(*rsa.PublicKey); ok {132 keyUsage |= x509.KeyUsageKeyEncipherment133 }134 cert := c.GetCertificate()135 cert.KeyUsage = KeyUsage(keyUsage)136 cert.ExtKeyUsage = ExtKeyUsage([]x509.ExtKeyUsage{137 x509.ExtKeyUsageServerAuth,138 x509.ExtKeyUsageClientAuth,139 })140 return cert141}142// CreateCertificateRequest creates a simple X.509 certificate request with the143// given common name and sans.144func CreateCertificateRequest(commonName string, sans []string, signer crypto.Signer) (*x509.CertificateRequest, error) {145 dnsNames, ips, emails, uris := SplitSANs(sans)146 asn1Data, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{147 Subject: pkix.Name{148 CommonName: commonName,149 },150 DNSNames: dnsNames,151 IPAddresses: ips,152 EmailAddresses: emails,153 URIs: uris,154 }, signer)155 if err != nil {156 return nil, errors.Wrap(err, "error creating certificate request")157 }158 // This should not fail159 return x509.ParseCertificateRequest(asn1Data)160}161// fixSubjectAltName makes sure to mark the SAN extension to critical if the162// subject is empty.163func fixSubjectAltName(cr *x509.CertificateRequest) {164 if asn1Subject, err := asn1.Marshal(cr.Subject.ToRDNSequence()); err == nil {165 if bytes.Equal(asn1Subject, emptyASN1Subject) {166 for i, ext := range cr.Extensions {167 if ext.Id.Equal(oidExtensionSubjectAltName) {...

Full Screen

Full Screen

uris

Using AI Code Generation

copy

Full Screen

1import (2func main() {3cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem")4if err != nil {5fmt.Println(err)6}7cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])8if err != nil {9fmt.Println(err)10}11for _, uri := range cert.Leaf.URIs {12fmt.Println(uri)13}14}

Full Screen

Full Screen

uris

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 caCert, err := ioutil.ReadFile("ca.crt")4 if err != nil {5 panic(err)6 }7 clientCert, err := ioutil.ReadFile("client.crt")8 if err != nil {9 panic(err)10 }11 clientKey, err := ioutil.ReadFile("client.key")12 if err != nil {13 panic(err)14 }15 caCertPool := x509.NewCertPool()16 caCertPool.AppendCertsFromPEM(caCert)17 clientCertPool := x509.NewCertPool()18 clientCertPool.AppendCertsFromPEM(clientCert)19 clientKeyPool := x509.NewCertPool()20 clientKeyPool.AppendCertsFromPEM(clientKey)21 tlsConfig := &tls.Config{22 }23 httpClient := &http.Client{24 Transport: &http.Transport{25 },26 }27 if err != nil {28 panic(err)29 }30 defer resp.Body.Close()31 body, err := ioutil.ReadAll(resp.Body)32 if err != nil {33 panic(err)34 }35 fmt.Println("response:", string(body))36}

Full Screen

Full Screen

uris

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cert, err := x509.LoadCertificateFromFile("cert.pem")4 if err != nil {5 fmt.Println("Error loading certificate: ", err)6 }7 uris := cert.URIs()8 for _, uri := range uris {9 fmt.Println("URI: ", uri)10 }11}

Full Screen

Full Screen

uris

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cert := new(x509.Certificate)4 cert.URIs = []*url.URL{5 &url.URL{Scheme: "http", Host: "www.example.com"},6 &url.URL{Scheme: "https", Host: "www.example.com"},7 }8 fmt.Printf("URIs: %s9}10Go | x509 Certificate Authority (CA) Example11Go | x509 Certificate Signing Request (CSR) Example12Go | x509 Certificate Revocation List (CRL) Example

Full Screen

Full Screen

uris

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 client := &http.Client{}5 resp, _ := client.Do(req)6 defer resp.Body.Close()7 for _, cert := range certs {8 for _, uri := range cert.URIs {9 fmt.Println(uri)10 }11 }12}

Full Screen

Full Screen

uris

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file, err := os.Open("cert.pem")4 if err != nil {5 fmt.Println(err)6 }7 defer file.Close()8 info, err := file.Stat()9 if err != nil {10 fmt.Println(err)11 }12 bytes := make([]byte, info.Size())13 _, err = file.Read(bytes)14 if err != nil {15 fmt.Println(err)16 }17 cert, err := x509.ParseCertificate(bytes)18 if err != nil {19 fmt.Println(err)20 }21 fmt.Println(uris)22}

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