Best K6 code snippet using x509.New
cert.go
Source:cert.go
...39// PEMtoCertificate converts pem to x50940func PEMtoCertificate(raw []byte) (*x509.Certificate, error) {41 block, _ := pem.Decode(raw)42 if block == nil {43 return nil, errors.New("No PEM block available")44 }45 if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {46 return nil, errors.New("Not a valid CERTIFICATE PEM block")47 }48 cert, err := x509.ParseCertificate(block.Bytes)49 if err != nil {50 return nil, err51 }52 return cert, nil53}54// PEMtoDER converts pem to der55func PEMtoDER(raw []byte) ([]byte, error) {56 block, _ := pem.Decode(raw)57 if block == nil {58 return nil, errors.New("No PEM block available")59 }60 if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {61 return nil, errors.New("Not a valid CERTIFICATE PEM block")62 }63 return block.Bytes, nil64}65// PEMtoCertificateAndDER converts pem to x509 and der66func PEMtoCertificateAndDER(raw []byte) (*x509.Certificate, []byte, error) {67 block, _ := pem.Decode(raw)68 if block == nil {69 return nil, nil, errors.New("No PEM block available")70 }71 if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {72 return nil, nil, errors.New("Not a valid CERTIFICATE PEM block")73 }74 cert, err := x509.ParseCertificate(block.Bytes)75 if err != nil {76 return nil, nil, err77 }78 return cert, block.Bytes, nil79}80// DERCertToPEM converts der to pem81func DERCertToPEM(der []byte) []byte {82 return pem.EncodeToMemory(83 &pem.Block{84 Type: "CERTIFICATE",85 Bytes: der,86 },87 )88}89// GetCriticalExtension returns a requested critical extension. It also remove it from the list90// of unhandled critical extensions91func GetCriticalExtension(cert *x509.Certificate, oid asn1.ObjectIdentifier) ([]byte, error) {92 for i, ext := range cert.UnhandledCriticalExtensions {93 if IntArrayEquals(ext, oid) {94 cert.UnhandledCriticalExtensions = append(cert.UnhandledCriticalExtensions[:i], cert.UnhandledCriticalExtensions[i+1:]...)95 break96 }97 }98 for _, ext := range cert.Extensions {99 if IntArrayEquals(ext.Id, oid) {100 return ext.Value, nil101 }102 }103 return nil, errors.New("Failed retrieving extension.")104}105// NewSelfSignedCert create a self signed certificate106func NewSelfSignedCert() ([]byte, interface{}, error) {107 privKey, err := NewECDSAKey()108 if err != nil {109 return nil, nil, err110 }111 testExtKeyUsage := []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}112 testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}113 extraExtensionData := []byte("extra extension")114 commonName := "test.example.com"115 template := x509.Certificate{116 SerialNumber: big.NewInt(1),117 Subject: pkix.Name{118 CommonName: commonName,119 Organization: []string{"Σ Acme Co"},120 Country: []string{"US"},121 ExtraNames: []pkix.AttributeTypeAndValue{122 {123 Type: []int{2, 5, 4, 42},124 Value: "Gopher",125 },126 // This should override the Country, above.127 {128 Type: []int{2, 5, 4, 6},129 Value: "NL",130 },131 },132 },133 NotBefore: time.Unix(1000, 0),134 NotAfter: time.Unix(100000, 0),135 SignatureAlgorithm: x509.ECDSAWithSHA384,136 SubjectKeyId: []byte{1, 2, 3, 4},137 KeyUsage: x509.KeyUsageCertSign,138 ExtKeyUsage: testExtKeyUsage,139 UnknownExtKeyUsage: testUnknownExtKeyUsage,140 BasicConstraintsValid: true,141 IsCA: true,142 OCSPServer: []string{"http://ocsp.example.com"},143 IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},144 DNSNames: []string{"test.example.com"},145 EmailAddresses: []string{"gopher@golang.org"},146 IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},147 PolicyIdentifiers: []asn1.ObjectIdentifier{[]int{1, 2, 3}},148 PermittedDNSDomains: []string{".example.com", "example.com"},149 CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},150 ExtraExtensions: []pkix.Extension{151 {152 Id: []int{1, 2, 3, 4},153 Value: extraExtensionData,154 },155 },156 }157 cert, err := x509.CreateCertificate(rand.Reader, &template, &template, &privKey.PublicKey, privKey)158 if err != nil {159 return nil, nil, err160 }161 return cert, privKey, nil162}163func CheckCertPKAgainstSK(x509Cert *x509.Certificate, privateKey interface{}) error {164 switch pub := x509Cert.PublicKey.(type) {165 case *rsa.PublicKey:166 priv, ok := privateKey.(*rsa.PrivateKey)167 if !ok {168 return errors.New("Private key type does not match public key type")169 }170 if pub.N.Cmp(priv.N) != 0 {171 return errors.New("Private key does not match public key")172 }173 case *ecdsa.PublicKey:174 priv, ok := privateKey.(*ecdsa.PrivateKey)175 if !ok {176 return errors.New("Private key type does not match public key type")177 }178 if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {179 return errors.New("Private key does not match public key")180 }181 default:182 return errors.New("Unknown public key algorithm")183 }184 return nil185}186func CheckCertAgainRoot(x509Cert *x509.Certificate, certPool *x509.CertPool) ([][]*x509.Certificate, error) {187 opts := x509.VerifyOptions{188 // TODO DNSName: "test.example.com",189 Roots: certPool,190 }191 return x509Cert.Verify(opts)192}193func CheckCertAgainstSKAndRoot(x509Cert *x509.Certificate, privateKey interface{}, certPool *x509.CertPool) error {194 if err := CheckCertPKAgainstSK(x509Cert, privateKey); err != nil {195 return err196 }...
csr_test.go
Source:csr_test.go
...22 return23}24func (pa *mockPA) WillingToIssue(id core.AcmeIdentifier) error {25 if id.Value == "bad-name.com" || id.Value == "other-bad-name.com" {26 return errors.New("")27 }28 return nil29}30func TestVerifyCSR(t *testing.T) {31 private, err := rsa.GenerateKey(rand.Reader, 2048)32 test.AssertNotError(t, err, "error generating test key")33 signedReqBytes, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{PublicKey: private.PublicKey, SignatureAlgorithm: x509.SHA256WithRSA}, private)34 test.AssertNotError(t, err, "error generating test CSR")35 signedReq, err := x509.ParseCertificateRequest(signedReqBytes)36 test.AssertNotError(t, err, "error parsing test CSR")37 brokenSignedReq := new(x509.CertificateRequest)38 *brokenSignedReq = *signedReq39 brokenSignedReq.Signature = []byte{1, 1, 1, 1}40 signedReqWithHosts := new(x509.CertificateRequest)41 *signedReqWithHosts = *signedReq42 signedReqWithHosts.DNSNames = []string{"a.com", "b.com"}43 signedReqWithLongCN := new(x509.CertificateRequest)44 *signedReqWithLongCN = *signedReq45 signedReqWithLongCN.Subject.CommonName = strings.Repeat("a", maxCNLength+1)46 signedReqWithBadNames := new(x509.CertificateRequest)47 *signedReqWithBadNames = *signedReq48 signedReqWithBadNames.DNSNames = []string{"bad-name.com", "other-bad-name.com"}49 signedReqWithEmailAddress := new(x509.CertificateRequest)50 *signedReqWithEmailAddress = *signedReq51 signedReqWithEmailAddress.EmailAddresses = []string{"foo@bar.com"}52 signedReqWithIPAddress := new(x509.CertificateRequest)53 *signedReqWithIPAddress = *signedReq54 signedReqWithIPAddress.IPAddresses = []net.IP{net.IPv4(1, 2, 3, 4)}55 cases := []struct {56 csr *x509.CertificateRequest57 maxNames int58 keyPolicy *goodkey.KeyPolicy59 pa core.PolicyAuthority60 regID int6461 expectedError error62 }{63 {64 &x509.CertificateRequest{},65 100,66 testingPolicy,67 &mockPA{},68 0,69 invalidPubKey,70 },71 {72 &x509.CertificateRequest{PublicKey: private.PublicKey},73 100,74 testingPolicy,75 &mockPA{},76 0,77 unsupportedSigAlg,78 },79 {80 brokenSignedReq,81 100,82 testingPolicy,83 &mockPA{},84 0,85 invalidSig,86 },87 {88 signedReq,89 100,90 testingPolicy,91 &mockPA{},92 0,93 invalidNoDNS,94 },95 {96 signedReqWithLongCN,97 100,98 testingPolicy,99 &mockPA{},100 0,101 errors.New("CN was longer than 64 bytes"),102 },103 {104 signedReqWithHosts,105 1,106 testingPolicy,107 &mockPA{},108 0,109 errors.New("CSR contains more than 1 DNS names"),110 },111 {112 signedReqWithBadNames,113 100,114 testingPolicy,115 &mockPA{},116 0,117 errors.New("policy forbids issuing for: \"bad-name.com\", \"other-bad-name.com\""),118 },119 {120 signedReqWithEmailAddress,121 100,122 testingPolicy,123 &mockPA{},124 0,125 invalidEmailPresent,126 },127 {128 signedReqWithIPAddress,129 100,130 testingPolicy,131 &mockPA{},...
certificates.go
Source:certificates.go
...9)10// GenerateTrustCA generates a new certificate authority for testing.11func GenerateTrustCA(pub crypto.PublicKey, priv crypto.PrivateKey) (*x509.Certificate, error) {12 cert := &x509.Certificate{13 SerialNumber: big.NewInt(0),14 Subject: pkix.Name{15 CommonName: "CA Root",16 },17 NotBefore: time.Now().Add(-time.Second),18 NotAfter: time.Now().Add(time.Hour),19 IsCA: true,20 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,21 BasicConstraintsValid: true,22 }23 certDER, err := x509.CreateCertificate(rand.Reader, cert, cert, pub, priv)24 if err != nil {25 return nil, err26 }27 cert, err = x509.ParseCertificate(certDER)28 if err != nil {29 return nil, err30 }31 return cert, nil32}33// GenerateIntermediate generates an intermediate certificate for testing using34// the parent certificate (likely a CA) and the provided keys.35func GenerateIntermediate(key crypto.PublicKey, parentKey crypto.PrivateKey, parent *x509.Certificate) (*x509.Certificate, error) {36 cert := &x509.Certificate{37 SerialNumber: big.NewInt(0),38 Subject: pkix.Name{39 CommonName: "Intermediate",40 },41 NotBefore: time.Now().Add(-time.Second),42 NotAfter: time.Now().Add(time.Hour),43 IsCA: true,44 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,45 BasicConstraintsValid: true,46 }47 certDER, err := x509.CreateCertificate(rand.Reader, cert, parent, key, parentKey)48 if err != nil {49 return nil, err50 }51 cert, err = x509.ParseCertificate(certDER)52 if err != nil {53 return nil, err54 }55 return cert, nil56}57// GenerateTrustCert generates a new trust certificate for testing. Unlike the58// intermediate certificates, this certificate should be used for signature59// only, not creating certificates.60func GenerateTrustCert(key crypto.PublicKey, parentKey crypto.PrivateKey, parent *x509.Certificate) (*x509.Certificate, error) {61 cert := &x509.Certificate{62 SerialNumber: big.NewInt(0),63 Subject: pkix.Name{64 CommonName: "Trust Cert",65 },66 NotBefore: time.Now().Add(-time.Second),67 NotAfter: time.Now().Add(time.Hour),68 IsCA: true,69 KeyUsage: x509.KeyUsageDigitalSignature,70 BasicConstraintsValid: true,71 }72 certDER, err := x509.CreateCertificate(rand.Reader, cert, parent, key, parentKey)73 if err != nil {74 return nil, err75 }76 cert, err = x509.ParseCertificate(certDER)...
New
Using AI Code Generation
1import (2func main() {3 cert, err := x509.ParseCertificate([]byte(certPEM))4 if err != nil {5 fmt.Println("Error in parsing certificate")6 }7 fmt.Println(cert)8}9import (10func main() {11 cert, err := x509.ParseCertificate([]byte(certPEM))12 if err != nil {13 fmt.Println("Error in parsing certificate")14 }15 fmt.Println(cert)16}17import (18func main() {19 cert, err := x509.ParseCertificate([]byte(certPEM))20 if err != nil {21 fmt.Println("Error in parsing certificate")22 }23 fmt.Println(cert)24}25import (26func main() {27 cert, err := x509.ParseCertificate([]byte(certPEM))28 if err != nil {29 fmt.Println("Error in parsing certificate")30 }31 fmt.Println(cert)32}33import (34func main() {35 cert, err := x509.ParseCertificate([]byte(certPEM))36 if err != nil {37 fmt.Println("Error in parsing certificate")38 }39 fmt.Println(cert)40}41import (42func main() {43 cert, err := x509.ParseCertificate([]byte(certPEM))44 if err != nil {45 fmt.Println("
New
Using AI Code Generation
1import (2func main() {3 certPool := x509.NewCertPool()4 certPool.AppendCertsFromPEM([]byte(`Certificate`))5 fmt.Println(certPool)6}7&{{[0xc0000a8000] 0 0}}8import (9func main() {10 certPool := x509.NewCertPool()11 cert, _ := x509.ParseCertificate([]byte(`Certificate`))12 certPool.AddCert(cert)13 fmt.Println(certPool)14}15&{{[0xc0000a8000] 0 0}}16import (17func main() {18 certPool := x509.NewCertPool()19 cert, _ := x509.ParseCertificate([]byte(`Certificate`))20 certPool.AddCert(cert)21 fmt.Println(certPool)22}23&{{[0xc0000a8000] 0 0}}24import (25func main() {26 certPool := x509.NewCertPool()27 certPool.AppendCertsFromPEM([]byte(`Certificate`))28 fmt.Println(certPool)29}30&{{[0xc0000a8000] 0 0}}31import (
New
Using AI Code Generation
1import (2func main() {3 cert, err := x509.ParseCertificate([]byte(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: []byte("test")})))4 if err != nil {5 fmt.Println("Error in parsing certificate")6 }7 fmt.Println(cert)8}9 Version: 3 (0x2)10 Serial Number: 0 (0x0)
New
Using AI Code Generation
1import (2func main() {3privateKey, err := rsa.GenerateKey(rand.Reader, 1024)4if err != nil {5panic(err)6}7dsaPrivateKey, err := dsa.GenerateKey(rand.Reader, 1024)8if err != nil {9panic(err)10}11ecdsaPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)12if err != nil {13panic(err)14}15template := x509.Certificate{16SerialNumber: big.NewInt(1),17Subject: pkix.Name{18Organization: []string{"Acme Co"},19},20NotBefore: time.Now(),21NotAfter: time.Now().Add(365 * 24 * time.Hour),22ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},23}24cert, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)25if err != nil {26panic(err)27}28dsaCert, err := x509.CreateCertificate(rand.Reader, &template, &template, &dsaPrivateKey.PublicKey, dsaPrivateKey)29if err != nil {30panic(err)31}32ecdsaCert, err := x509.CreateCertificate(rand.Reader, &template, &template, &ecdsaPrivateKey.PublicKey, ecdsaPrivateKey)33if err != nil {34panic(err)35}36parsedCert, err := x509.ParseCertificate(cert)37if err != nil {38panic(err)39}40dsaParsedCert, err := x509.ParseCertificate(dsaCert)41if err != nil {42panic(err)43}44ecdsaParsedCert, err := x509.ParseCertificate(ecdsaCert)45if err != nil {46panic(err)47}48fmt.Printf("RSA Certificate: %v49fmt.Printf("DSA Certificate: %v
New
Using AI Code Generation
1func main() {2 cert, err := x509.ParseCertificate([]byte("cert"))3 if err != nil {4 fmt.Println("error in parsing certificate")5 }6 fmt.Println(cert)7}8func main() {9 cert, err := x509.ParseCertificate([]byte("cert"))10 if err != nil {11 fmt.Println("error in parsing certificate")12 }13 fmt.Println(cert)14}15func main() {16 cert, err := x509.ParseCertificate([]byte("cert"))17 if err != nil {18 fmt.Println("error in parsing certificate")19 }20 fmt.Println(cert)21}22func main() {23 cert, err := x509.ParseCertificate([]byte("cert"))24 if err != nil {25 fmt.Println("error in parsing certificate")26 }27 fmt.Println(cert)28}29func main() {30 cert, err := x509.ParseCertificate([]byte("cert"))31 if err != nil {32 fmt.Println("error in parsing certificate")33 }34 fmt.Println(cert)35}36func main() {37 cert, err := x509.ParseCertificate([]byte("cert"))38 if err != nil {39 fmt.Println("error in parsing certificate")40 }41 fmt.Println(cert)42}43func main() {44 cert, err := x509.ParseCertificate([]byte("cert"))45 if err != nil {46 fmt.Println("error in parsing certificate")47 }48 fmt.Println(cert)49}50func main() {51 cert, err := x509.ParseCertificate([]byte("cert"))52 if err != nil {53 fmt.Println("error in parsing certificate")54 }55 fmt.Println(cert)56}57func main() {58 cert, err := x509.ParseCertificate([]byte("cert"))59 if err != nil {
New
Using AI Code Generation
1x509Cert := x509.New()2x509Cert.ParseCertificate(cert)3x509Cert.SetIssuer(cert.Issuer)4x509Cert.SetSubject(cert.Subject)5x509Cert.SetNotBefore(cert.NotBefore)6x509Cert.SetNotAfter(cert.NotAfter)7x509Cert.GetIssuer()8x509Cert.GetSubject()9x509Cert.GetNotBefore()10x509Cert.GetNotAfter()11x509Cert.GetSerialNumber()12x509Cert.GetPublicKey()13x509Cert.GetSignature()14x509Cert.GetSignatureAlgorithm()15x509Cert.GetPublicKeyAlgorithm()16x509Cert.GetVersion()17x509Cert.GetRaw()18x509Cert.GetRawSubject()19x509Cert.GetRawIssuer()20x509Cert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature)21x509Cert.VerifyHostname("")
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!