3 # Google - parsing subject field
5 # See the LICENSE file for legal information regarding use of this file.
7 """Class representing an X.509 certificate."""
9 from .utils.asn1parser import ASN1Parser
10 from .utils.cryptomath import *
11 from .utils.keyfactory import _createPublicRSAKey
12 from .utils.pem import *
16 """This class represents an X.509 certificate.
18 @type bytes: L{bytearray} of unsigned bytes
19 @ivar bytes: The DER-encoded ASN.1 certificate
21 @type publicKey: L{tlslite.utils.rsakey.RSAKey}
22 @ivar publicKey: The subject public key from the certificate.
24 @type subject: L{bytearray} of unsigned bytes
25 @ivar subject: The DER-encoded ASN.1 subject distinguished name.
29 self.bytes = bytearray(0)
34 """Parse a PEM-encoded X.509 certificate.
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).
42 bytes = dePem(s, "CERTIFICATE")
43 self.parseBinary(bytes)
46 def parseBinary(self, bytes):
47 """Parse a DER-encoded X.509 certificate.
49 @type bytes: str or L{bytearray} of unsigned bytes
50 @param bytes: A DER-encoded X.509 certificate.
53 self.bytes = bytearray(bytes)
56 #Get the tbsCertificate
57 tbsCertificateP = p.getChild(0)
59 #Is the optional version field present?
60 #This determines which index the key is at.
61 if tbsCertificateP.value[0]==0xA0:
62 subjectPublicKeyInfoIndex = 6
64 subjectPublicKeyInfoIndex = 5
67 self.subject = tbsCertificateP.getChildBytes(\
68 subjectPublicKeyInfoIndex - 1)
70 #Get the subjectPublicKeyInfo
71 subjectPublicKeyInfoP = tbsCertificateP.getChild(\
72 subjectPublicKeyInfoIndex)
75 algorithmP = subjectPublicKeyInfoP.getChild(0)
76 rsaOID = algorithmP.value
77 if list(rsaOID) != [6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0]:
78 raise SyntaxError("Unrecognized AlgorithmIdentifier")
80 #Get the subjectPublicKey
81 subjectPublicKeyP = subjectPublicKeyInfoP.getChild(1)
83 #Adjust for BIT STRING encapsulation
84 if (subjectPublicKeyP.value[0] !=0):
86 subjectPublicKeyP = ASN1Parser(subjectPublicKeyP.value[1:])
88 #Get the modulus and exponent
89 modulusP = subjectPublicKeyP.getChild(0)
90 publicExponentP = subjectPublicKeyP.getChild(1)
92 #Decode them into numbers
93 n = bytesToNumber(modulusP.value)
94 e = bytesToNumber(publicExponentP.value)
96 #Create a public key instance
97 self.publicKey = _createPublicRSAKey(n, e)
99 def getFingerprint(self):
100 """Get the hex-encoded fingerprint of this certificate.
103 @return: A hex-encoded fingerprint.
105 return b2a_hex(SHA1(self.bytes))
107 def writeBytes(self):