How to use issuer method of x509 Package

Best K6 code snippet using x509.issuer

ocsp.go

Source:ocsp.go Github

copy

Full Screen

...346 SigRequredErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x05}347 UnauthorizedErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x06}348)349// CheckSignatureFrom checks that the signature in resp is a valid signature350// from issuer. This should only be used if resp.Certificate is nil. Otherwise,351// the OCSP response contained an intermediate certificate that created the352// signature. That signature is checked by ParseResponse and only353// resp.Certificate remains to be validated.354func (resp *Response) CheckSignatureFrom(issuer *x509.Certificate) error {355 return issuer.CheckSignature(resp.SignatureAlgorithm, resp.TBSResponseData, resp.Signature)356}357// ParseError results from an invalid OCSP response.358type ParseError string359func (p ParseError) Error() string {360 return string(p)361}362// ParseRequest parses an OCSP request in DER form. It only supports363// requests for a single certificate. Signed requests are not supported.364// If a request includes a signature, it will result in a ParseError.365func ParseRequest(bytes []byte) (*Request, []pkix.Extension, error) {366 var req ocspRequest367 rest, err := asn1.Unmarshal(bytes, &req)368 if err != nil {369 return nil, nil, err370 }371 if len(rest) > 0 {372 return nil, nil, ParseError("trailing data in OCSP request")373 }374 if len(req.TBSRequest.RequestList) == 0 {375 return nil, nil, ParseError("OCSP request contains no request body")376 }377 innerRequest := req.TBSRequest.RequestList[0]378 hashFunc := getHashAlgorithmFromOID(innerRequest.Cert.HashAlgorithm.Algorithm)379 if hashFunc == crypto.Hash(0) {380 return nil, nil, ParseError("OCSP request uses unknown hash function")381 }382 return &Request{383 HashAlgorithm: hashFunc,384 IssuerNameHash: innerRequest.Cert.NameHash,385 IssuerKeyHash: innerRequest.Cert.IssuerKeyHash,386 SerialNumber: innerRequest.Cert.SerialNumber,387 }, req.TBSRequest.ExtensionList, nil388}389// ParseResponse parses an OCSP response in DER form. It only supports390// responses for a single certificate. If the response contains a certificate391// then the signature over the response is checked. If issuer is not nil then392// it will be used to validate the signature or embedded certificate.393//394// Invalid signatures or parse failures will result in a ParseError. Error395// responses will result in a ResponseError.396func ParseResponse(bytes []byte, issuer *x509.Certificate) (*Response, error) {397 return ParseResponseForCert(bytes, nil, issuer)398}399// ParseResponseForCert parses an OCSP response in DER form and searches for a400// Response relating to cert. If such a Response is found and the OCSP response401// contains a certificate then the signature over the response is checked. If402// issuer is not nil then it will be used to validate the signature or embedded403// certificate.404//405// Invalid signatures or parse failures will result in a ParseError. Error406// responses will result in a ResponseError.407func ParseResponseForCert(bytes []byte, cert, issuer *x509.Certificate) (*Response, error) {408 var resp responseASN1409 rest, err := asn1.Unmarshal(bytes, &resp)410 if err != nil {411 return nil, err412 }413 if len(rest) > 0 {414 return nil, ParseError("trailing data in OCSP response")415 }416 if status := ResponseStatus(resp.Status); status != Success {417 return nil, ResponseError{status}418 }419 if !resp.Response.ResponseType.Equal(idPKIXOCSPBasic) {420 return nil, ParseError("bad OCSP response type")421 }422 var basicResp basicResponse423 rest, err = asn1.Unmarshal(resp.Response.Response, &basicResp)424 if err != nil {425 return nil, err426 }427 if len(basicResp.Certificates) > 1 {428 return nil, ParseError("OCSP response contains bad number of certificates")429 }430 if n := len(basicResp.TBSResponseData.Responses); n == 0 || cert == nil && n > 1 {431 return nil, ParseError("OCSP response contains bad number of responses")432 }433 ret := &Response{434 TBSResponseData: basicResp.TBSResponseData.Raw,435 Signature: basicResp.Signature.RightAlign(),436 SignatureAlgorithm: getSignatureAlgorithmFromOID(basicResp.SignatureAlgorithm.Algorithm),437 }438 if len(basicResp.Certificates) > 0 {439 ret.Certificate, err = x509.ParseCertificate(basicResp.Certificates[0].FullBytes)440 if err != nil {441 return nil, err442 }443 if err := ret.CheckSignatureFrom(ret.Certificate); err != nil {444 return nil, ParseError("bad OCSP signature")445 }446 if issuer != nil {447 if err := issuer.CheckSignature(ret.Certificate.SignatureAlgorithm, ret.Certificate.RawTBSCertificate, ret.Certificate.Signature); err != nil {448 return nil, ParseError("bad signature on embedded certificate")449 }450 }451 } else if issuer != nil {452 if err := ret.CheckSignatureFrom(issuer); err != nil {453 return nil, ParseError("bad OCSP signature")454 }455 }456 var r singleResponse457 for _, resp := range basicResp.TBSResponseData.Responses {458 if cert == nil || cert.SerialNumber.Cmp(resp.CertID.SerialNumber) == 0 {459 r = resp460 break461 }462 }463 for _, ext := range r.SingleExtensions {464 if ext.Critical {465 return nil, ParseError("unsupported critical extension")466 }467 }468 ret.Extensions = r.SingleExtensions469 ret.SerialNumber = r.CertID.SerialNumber470 for h, oid := range hashOIDs {471 if r.CertID.HashAlgorithm.Algorithm.Equal(oid) {472 ret.IssuerHash = h473 break474 }475 }476 if ret.IssuerHash == 0 {477 return nil, ParseError("unsupported issuer hash algorithm")478 }479 switch {480 case bool(r.Good):481 ret.Status = Good482 case bool(r.Unknown):483 ret.Status = Unknown484 default:485 ret.Status = Revoked486 ret.RevokedAt = r.Revoked.RevocationTime487 ret.RevocationReason = int(r.Revoked.Reason)488 }489 ret.ProducedAt = basicResp.TBSResponseData.ProducedAt490 ret.ThisUpdate = r.ThisUpdate491 ret.NextUpdate = r.NextUpdate492 return ret, nil493}494// RequestOptions contains options for constructing OCSP requests.495type RequestOptions struct {496 // Hash contains the hash function that should be used when497 // constructing the OCSP request. If zero, SHA-1 will be used.498 Hash crypto.Hash499}500func (opts *RequestOptions) hash() crypto.Hash {501 if opts == nil || opts.Hash == 0 {502 // SHA-1 is nearly universally used in OCSP.503 return crypto.SHA1504 }505 return opts.Hash506}507// CreateRequest returns a DER-encoded, OCSP request for the status of cert. If508// opts is nil then sensible defaults are used.509func CreateRequest(cert, issuer *x509.Certificate, opts *RequestOptions) ([]byte, error) {510 hashFunc := opts.hash()511 // OCSP seems to be the only place where these raw hash identifiers are512 // used. I took the following from513 // http://msdn.microsoft.com/en-us/library/ff635603.aspx514 _, ok := hashOIDs[hashFunc]515 if !ok {516 return nil, x509.ErrUnsupportedAlgorithm517 }518 if !hashFunc.Available() {519 return nil, x509.ErrUnsupportedAlgorithm520 }521 h := opts.hash().New()522 var publicKeyInfo struct {523 Algorithm pkix.AlgorithmIdentifier524 PublicKey asn1.BitString525 }526 if _, err := asn1.Unmarshal(issuer.RawSubjectPublicKeyInfo, &publicKeyInfo); err != nil {527 return nil, err528 }529 h.Write(publicKeyInfo.PublicKey.RightAlign())530 issuerKeyHash := h.Sum(nil)531 h.Reset()532 h.Write(issuer.RawSubject)533 issuerNameHash := h.Sum(nil)534 req := &Request{535 HashAlgorithm: hashFunc,536 IssuerNameHash: issuerNameHash,537 IssuerKeyHash: issuerKeyHash,538 SerialNumber: cert.SerialNumber,539 }540 return req.Marshal()541}542// CreateResponse returns a DER-encoded OCSP response with the specified contents.543// The fields in the response are populated as follows:544//545// The responder cert is used to populate the ResponderName field, and the certificate546// itself is provided alongside the OCSP response signature.547//548// The issuer cert is used to puplate the IssuerNameHash and IssuerKeyHash fields.549//550// The template is used to populate the SerialNumber, RevocationStatus, RevokedAt,551// RevocationReason, ThisUpdate, and NextUpdate fields.552//553// If template.IssuerHash is not set, SHA1 will be used.554//555// The ProducedAt date is automatically set to the current date, to the nearest minute.556func CreateResponse(issuer, responderCert *x509.Certificate, template Response, priv crypto.Signer) ([]byte, error) {557 var publicKeyInfo struct {558 Algorithm pkix.AlgorithmIdentifier559 PublicKey asn1.BitString560 }561 if _, err := asn1.Unmarshal(issuer.RawSubjectPublicKeyInfo, &publicKeyInfo); err != nil {562 return nil, err563 }564 if template.IssuerHash == 0 {565 template.IssuerHash = crypto.SHA1566 }567 hashOID := getOIDFromHashAlgorithm(template.IssuerHash)568 if hashOID == nil {569 return nil, errors.New("unsupported issuer hash algorithm")570 }571 if !template.IssuerHash.Available() {572 return nil, fmt.Errorf("issuer hash algorithm %v not linked into binarya", template.IssuerHash)573 }574 h := template.IssuerHash.New()575 h.Write(publicKeyInfo.PublicKey.RightAlign())576 issuerKeyHash := h.Sum(nil)577 h.Reset()578 h.Write(issuer.RawSubject)579 issuerNameHash := h.Sum(nil)580 innerResponse := singleResponse{581 CertID: certID{582 HashAlgorithm: pkix.AlgorithmIdentifier{583 Algorithm: hashOID,584 Parameters: asn1.RawValue{Tag: 5 /* ASN.1 NULL */},585 },586 NameHash: issuerNameHash,587 IssuerKeyHash: issuerKeyHash,588 SerialNumber: template.SerialNumber,589 },590 ThisUpdate: template.ThisUpdate.UTC(),591 NextUpdate: template.NextUpdate.UTC(),592 SingleExtensions: template.ExtraExtensions,593 }594 switch template.Status {595 case Good:596 innerResponse.Good = true597 case Unknown:598 innerResponse.Unknown = true599 case Revoked:600 innerResponse.Revoked = revokedInfo{601 RevocationTime: template.RevokedAt.UTC(),...

Full Screen

Full Screen

issuer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 priv, err := rsa.GenerateKey(rand.Reader, 2048)4 if err != nil {5 fmt.Fprintf(os.Stderr, "Failed to generate private key: %s", err)6 os.Exit(1)7 }8 notBefore := time.Now()9 notAfter := notBefore.Add(365 * 24 * time.Hour)10 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)11 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)12 if err != nil {13 fmt.Fprintf(os.Stderr, "Failed to generate serial number: %s", err)14 os.Exit(1)15 }16 template := x509.Certificate{17 Subject: pkix.Name{18 Organization: []string{"Acme Co"},19 },20 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},21 IPAddresses: []net.IP{net.ParseIP("

Full Screen

Full Screen

issuer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cert, err := ioutil.ReadFile("cert.pem")4 if err != nil {5 fmt.Println("Error reading the certificate file")6 }7 block, _ := pem.Decode(cert)8 if block == nil {9 fmt.Println("Error parsing the certificate file")10 }11 parsedCert, err := x509.ParseCertificate(block.Bytes)12 if err != nil {13 fmt.Println("Error extracting the certificate")14 }15 fmt.Println(parsedCert.Issuer)16}

Full Screen

Full Screen

issuer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cert, err := ioutil.ReadFile("cert.pem")4 if err != nil {5 panic(err)6 }7 certParsed, err := x509.ParseCertificate(cert)8 if err != nil {9 panic(err)10 }11 fmt.Println(certParsed.Issuer)12}13{C=US,O=Let's Encrypt,CN=Let's Encrypt Authority X3}

Full Screen

Full Screen

issuer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cert, err := ioutil.ReadFile("cert.pem")4 if err != nil {5 fmt.Println("Error reading file")6 }7 block, _ := pem.Decode(cert)8 certObj, _ := x509.ParseCertificate(block.Bytes)9 fmt.Println(certObj.Issuer)10}11{C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3}

Full Screen

Full Screen

issuer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 certPEMBlock, err := ioutil.ReadFile("public.crt")4 if err != nil {5 panic(err)6 }7 cert, err := x509.ParseCertificate(certPEMBlock)8 if err != nil {9 panic(err)10 }11 fmt.Println(issuer)12}13{C:US ST:CA L:San Francisco O:Acme, Inc. OU:Engineering CN:Acme Root CA}

Full Screen

Full Screen

issuer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 certPEMBlock, err := ioutil.ReadFile("cert.pem")4 if err != nil {5 fmt.Println("Error reading certificate file")6 }7 certDERBlock, _ := pem.Decode(certPEMBlock)8 cert, err := x509.ParseCertificate(certDERBlock.Bytes)9 if err != nil {10 fmt.Println("Error parsing certificate")11 }12 fmt.Println(issuer)13}14{O=My Company Name LTD., L=Some-State, C=US}

Full Screen

Full Screen

issuer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 pk, err := ioutil.ReadFile("public.pem")4 if err != nil {5 panic(err)6 }7 block, _ := pem.Decode(pk)8 cert, err := x509.ParseCertificate(block.Bytes)9 if err != nil {10 panic(err)11 }12 fmt.Println(cert.Issuer)13}14import (15func main() {16 pk, err := ioutil.ReadFile("public.pem")17 if err != nil {18 panic(err)19 }20 block, _ := pem.Decode(pk)21 cert, err := x509.ParseCertificate(block.Bytes)22 if err != nil {23 panic(err)24 }25 fmt.Println(cert.Subject)26}27import (28func main() {29 pk, err := ioutil.ReadFile("public.pem")30 if err != nil {31 panic(err)32 }33 block, _ := pem.Decode(pk)

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