forked from github/smimesign
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
109 lines (87 loc) · 2.39 KB
/
utils.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
106
107
108
109
package main
import (
"bytes"
"crypto/sha1"
"crypto/x509"
"encoding/asn1"
"encoding/hex"
"regexp"
"strings"
)
// normalizeFingerprint converts a string fingerprint to hex, removing leading
// "0x", if present.
func normalizeFingerprint(sfpr string) []byte {
if len(sfpr) == 0 {
return nil
}
if strings.HasPrefix(sfpr, "0x") {
sfpr = sfpr[2:]
}
hfpr, err := hex.DecodeString(sfpr)
if err != nil {
return nil
}
return hfpr
}
// certHasFingerprint checks if the given certificate has the given fingerprint.
func certHasFingerprint(cert *x509.Certificate, fpr []byte) bool {
if len(fpr) == 0 {
return false
}
return bytes.HasSuffix(certFingerprint(cert), fpr)
}
// certHexFingerprint calculated the hex SHA1 fingerprint of a certificate.
func certHexFingerprint(cert *x509.Certificate) string {
return hex.EncodeToString(certFingerprint(cert))
}
// certFingerprint calculated the SHA1 fingerprint of a certificate.
func certFingerprint(cert *x509.Certificate) []byte {
if len(cert.Raw) == 0 {
return nil
}
fpr := sha1.Sum(cert.Raw)
return fpr[:]
}
// normalizeEmail attempts to extract an email address from a user-id string.
func normalizeEmail(email string) string {
name, _, email := parseUserID(email)
if len(email) > 0 {
return email
}
if strings.ContainsRune(name, '@') {
return name
}
return ""
}
var (
oidEmailAddress = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1}
oidCommonName = asn1.ObjectIdentifier{2, 5, 4, 3}
)
// certHasEmail checks if a certificate contains the given email address in its
// subject (CN/emailAddress) or SAN fields.
func certHasEmail(cert *x509.Certificate, email string) bool {
for _, other := range certEmails(cert) {
if other == email {
return true
}
}
return false
}
// borrowed from http://emailregex.com/
var emailRegexp = regexp.MustCompile(`(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)`)
// certEmails extracts email addresses from a certificate's subject
// (CN/emailAddress) and SAN extensions.
func certEmails(cert *x509.Certificate) []string {
// From SAN
emails := cert.EmailAddresses
// From CN and emailAddress fields in subject.
for _, name := range cert.Subject.Names {
if !name.Type.Equal(oidEmailAddress) && !name.Type.Equal(oidCommonName) {
continue
}
if email, isStr := name.Value.(string); isStr && emailRegexp.MatchString(email) {
emails = append(emails, email)
}
}
return emails
}