github.com/zmap/zcrypto@v0.0.0-20240512203510-0fef58d9a9db/x509/parse_test.go (about)

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package x509
     6  
     7  import (
     8  	"encoding/pem"
     9  	"io/ioutil"
    10  	"testing"
    11  )
    12  
    13  const testdataPrefix = "testdata/"
    14  
    15  func TestDetectSelfSigned(t *testing.T) {
    16  	tests := []struct {
    17  		Filename string
    18  		Expected bool
    19  	}{
    20  		{
    21  			Filename: "self-signed.pem",
    22  			Expected: true,
    23  		},
    24  		{
    25  			Filename: "self-signed-invalid-sig.pem",
    26  			Expected: false,
    27  		},
    28  		{
    29  			Filename: "self-signed-invalid-name.pem",
    30  			Expected: false,
    31  		},
    32  		{
    33  			Filename: "dadrian.io.pem",
    34  			Expected: false,
    35  		},
    36  		{
    37  			Filename: "self-signed-md5-rsa.pem",
    38  			Expected: true,
    39  		},
    40  	}
    41  	for _, test := range tests {
    42  		path := testdataPrefix + test.Filename
    43  		b, err := ioutil.ReadFile(path)
    44  		if err != nil {
    45  			t.Fatalf("could not open %s: %s", test.Filename, err)
    46  		}
    47  		p, _ := pem.Decode(b)
    48  		if p == nil {
    49  			t.Fatalf("bad pem %s", test.Filename)
    50  		}
    51  		c, err := ParseCertificate(p.Bytes)
    52  		if err != nil {
    53  			t.Fatalf("could not parse %s: %s", test.Filename, err)
    54  		}
    55  		if c.SelfSigned != test.Expected {
    56  			t.Errorf("expected %s to have SelfSigned = %t", test.Filename, test.Expected)
    57  			t.Fail()
    58  		}
    59  	}
    60  }
    61  
    62  func TestParseEmailInDN(t *testing.T) {
    63  	const expectedEmail = "ca-winshuttle@dfn.de"
    64  	b, err := ioutil.ReadFile(testdataPrefix + "email-in-subject.pem")
    65  	if err != nil {
    66  		t.Fatalf("could not open file: %s", err)
    67  	}
    68  	p, _ := pem.Decode(b)
    69  	if p == nil {
    70  		t.Fatalf("bad pem")
    71  	}
    72  	c, err := ParseCertificate(p.Bytes)
    73  	if err != nil {
    74  		t.Fatalf("could not parse: %s", err)
    75  	}
    76  	if len(c.Subject.EmailAddress) != 1 {
    77  		t.Error("did not parse email address")
    78  	}
    79  	if email := c.Subject.EmailAddress[0]; email != expectedEmail {
    80  		t.Errorf("mismatched email address, expected %s, got %s", expectedEmail, email)
    81  	}
    82  }