1
2
3
4
5
6
7 """Class representing an X.509 certificate."""
8
9 from .utils.asn1parser import ASN1Parser
10 from .utils.cryptomath import *
11 from .utils.keyfactory import _createPublicRSAKey
12 from .utils.pem import *
13
14
16 """This class represents an X.509 certificate.
17
18 @type bytes: L{bytearray} of unsigned bytes
19 @ivar bytes: The DER-encoded ASN.1 certificate
20
21 @type publicKey: L{tlslite.utils.rsakey.RSAKey}
22 @ivar publicKey: The subject public key from the certificate.
23
24 @type subject: L{bytearray} of unsigned bytes
25 @ivar subject: The DER-encoded ASN.1 subject distinguished name.
26 """
27
32
34 """Parse a PEM-encoded X.509 certificate.
35
36 @type s: str
37 @param s: A PEM-encoded X.509 certificate (i.e. a base64-encoded
38 certificate wrapped with "-----BEGIN CERTIFICATE-----" and
39 "-----END CERTIFICATE-----" tags).
40 """
41
42 bytes = dePem(s, "CERTIFICATE")
43 self.parseBinary(bytes)
44 return self
45
47 """Parse a DER-encoded X.509 certificate.
48
49 @type bytes: str or L{bytearray} of unsigned bytes
50 @param bytes: A DER-encoded X.509 certificate.
51 """
52
53 if isinstance(bytes, type("")):
54 bytes = stringToBytes(bytes)
55
56 self.bytes = bytes
57 p = ASN1Parser(bytes)
58
59
60 tbsCertificateP = p.getChild(0)
61
62
63
64 if tbsCertificateP.value[0]==0xA0:
65 subjectPublicKeyInfoIndex = 6
66 else:
67 subjectPublicKeyInfoIndex = 5
68
69
70 self.subject = tbsCertificateP.getChildBytes(\
71 subjectPublicKeyInfoIndex - 1)
72
73
74 subjectPublicKeyInfoP = tbsCertificateP.getChild(\
75 subjectPublicKeyInfoIndex)
76
77
78 algorithmP = subjectPublicKeyInfoP.getChild(0)
79 rsaOID = algorithmP.value
80 if list(rsaOID) != [6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0]:
81 raise SyntaxError("Unrecognized AlgorithmIdentifier")
82
83
84 subjectPublicKeyP = subjectPublicKeyInfoP.getChild(1)
85
86
87 if (subjectPublicKeyP.value[0] !=0):
88 raise SyntaxError()
89 subjectPublicKeyP = ASN1Parser(subjectPublicKeyP.value[1:])
90
91
92 modulusP = subjectPublicKeyP.getChild(0)
93 publicExponentP = subjectPublicKeyP.getChild(1)
94
95
96 n = bytesToNumber(modulusP.value)
97 e = bytesToNumber(publicExponentP.value)
98
99
100 self.publicKey = _createPublicRSAKey(n, e)
101
103 """Get the hex-encoded fingerprint of this certificate.
104
105 @rtype: str
106 @return: A hex-encoded fingerprint.
107 """
108 return sha1(bytesToString(self.bytes)).hexdigest()
109
112