forked from SSLMate/go-pkcs12
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpkcs12_test.go
105 lines (88 loc) · 2.49 KB
/
pkcs12_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pkcs12
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
_ "embed"
"encoding/pem"
"testing"
)
//go:embed test-data/testing_at_example_com.p12
var fileTestingAtExampleCom []byte
//go:embed test-data/windows_azure_tools.p12
var fileWindowsAzureTools []byte
var testdata = map[string][]byte{
// 'null' password test case
"Windows Azure Tools": fileWindowsAzureTools,
// empty string password test case
"[email protected]": fileTestingAtExampleCom,
}
func TestPfx(t *testing.T) {
for commonName, p12 := range testdata {
t.Run(commonName, func(t *testing.T) {
priv, cert, err := Decode(p12, "")
if err != nil {
t.Fatal(err)
}
if err := priv.(*rsa.PrivateKey).Validate(); err != nil {
t.Errorf("error while validating private key: %v", err)
}
if cert.Subject.CommonName != commonName {
t.Errorf("expected common name to be %q, but found %q", commonName, cert.Subject.CommonName)
}
})
}
}
func TestPEM(t *testing.T) {
for commonName, p12 := range testdata {
t.Run(commonName, func(t *testing.T) {
blocks, err := ToPEM(p12, "")
if err != nil {
t.Fatalf("error while converting to PEM: %s", err)
}
var pemData []byte
for _, b := range blocks {
pemData = append(pemData, pem.EncodeToMemory(b)...)
}
cert, err := tls.X509KeyPair(pemData, pemData)
if err != nil {
t.Errorf("err while converting to key pair: %v", err)
}
config := tls.Config{
Certificates: []tls.Certificate{cert},
}
config.BuildNameToCertificate()
if _, exists := config.NameToCertificate[commonName]; !exists {
t.Errorf("did not find our cert in PEM?: %v", config.NameToCertificate)
}
})
}
}
func TestTrustStore(t *testing.T) {
for commonName, p12 := range testdata {
t.Run(commonName, func(t *testing.T) {
_, cert, err := Decode(p12, "")
if err != nil {
t.Fatal(err)
}
pfxData, err := EncodeTrustStore(rand.Reader, []*x509.Certificate{cert}, "password")
if err != nil {
t.Fatal(err)
}
decodedCerts, err := DecodeTrustStore(pfxData, "password")
if err != nil {
t.Fatal(err)
}
if len(decodedCerts) != 1 {
t.Fatal("Unexpected number of certs")
}
if decodedCerts[0].Subject.CommonName != commonName {
t.Errorf("expected common name to be %q, but found %q", commonName, decodedCerts[0].Subject.CommonName)
}
})
}
}