Debian Codegraph @

src/pem/_core.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 """
4 Framework agnostic PEM file parsing functions.
5 """
6
7 from __future__ import absolute_import, division, print_function
8
9 import hashlib
10 import re
11
12 from ._compat import ABC, PY2, text_type
13
14
15 # mypy hack: Import typing information without actually importing anything.
16 MYPY = False
17 if MYPY: # pragma: nocover
18 from typing import List, Any, Union, AnyStr, Optional, Dict, Type # noqa
19
20
21 class AbstractPEMObject(ABC):
22 """
23 Base class for parsed objects.
24 """
25
26 def __init__(self, pem_bytes):
27 # type: (Union[text_type, bytes]) -> None
28 if isinstance(pem_bytes, text_type):
29 self._pem_bytes = pem_bytes.encode("ascii") # type: bytes
30 else:
31 self._pem_bytes = pem_bytes # type: bytes
32 self._sha1_hexdigest = None # type: Optional[str]
33
34 def __str__(self):
35 # type: () -> str
36 """
37 Return the PEM-encoded content as a native :obj:`str`.
38 """
39 if not PY2:
40 return self._pem_bytes.decode("ascii")
41 return self._pem_bytes
42
43 def __repr__(self):
44 # type: () -> str
45 return "<{0}(PEM string with SHA-1 digest {1!r})>".format(
46 self.__class__.__name__, self.sha1_hexdigest
47 )
48
49 @property
50 def sha1_hexdigest(self):
51 # type: () -> str
52 """
53 A SHA-1 digest of the whole object for easy differentiation.
54
55 .. versionadded:: 18.1.0
56 """
57 if self._sha1_hexdigest is None:
58 self._sha1_hexdigest = hashlib.sha1(self._pem_bytes).hexdigest()
59
60 return self._sha1_hexdigest
61
62 def as_bytes(self):
63 # type: () -> bytes
64 """
65 Return the PEM-encoded content as :obj:`bytes`.
66
67 .. versionadded:: 16.1.0
68 """
69 return self._pem_bytes
70
71 def as_text(self):
72 # type: () -> text_type
73 """
74 Return the PEM-encoded content as Unicode text.
75
76 .. versionadded:: 18.1.0
77 """
78 return self._pem_bytes.decode("utf-8")
79
80 def __eq__(self, other):
81 # type: (object) -> Union[NotImplemented, bool]
82 if not isinstance(other, type(self)):
83 return NotImplemented
84
85 return (
86 type(self) == type(other) and self._pem_bytes == other._pem_bytes
87 )
88
89 def __ne__(self, other):
90 # type: (object) -> Union[NotImplemented, bool]
91 if not isinstance(other, type(self)):
92 return NotImplemented
93
94 return type(self) != type(other) or self._pem_bytes != other._pem_bytes
95
96 def __hash__(self):
97 # type: () -> int
98 return hash(self._pem_bytes)
99
100
101 class Certificate(AbstractPEMObject):
102 """
103 A certificate.
104 """
105
106
107 class CertificateRequest(AbstractPEMObject):
108 """
109 A certificate signing request.
110
111 .. versionadded:: 17.1.0
112 """
113
114
115 class CertificateRevocationList(AbstractPEMObject):
116 """
117 A certificate revocation list.
118
119 .. versionadded:: 18.2.0
120 """
121
122
123 class Key(AbstractPEMObject):
124 """
125 A key of unknown type.
126 """
127
128
129 class PrivateKey(Key):
130 """
131 A private key of unknown type.
132
133 .. versionadded:: 19.1.0
134 """
135
136
137 class PublicKey(Key):
138 """
139 A public key of unknown type.
140
141 .. versionadded:: 19.1.0
142 """
143
144
145 class RSAPrivateKey(PrivateKey):
146 """
147 A private RSA key.
148 """
149
150
151 class RSAPublicKey(PublicKey):
152 """
153 A public RSA key.
154
155 .. versionadded:: 19.1.0
156 """
157
158
159 class DHParameters(AbstractPEMObject):
160 """
161 Diffie-Hellman parameters for DHE.
162 """
163
164
165 _PEM_TO_CLASS = {
166 b"CERTIFICATE": Certificate,
167 b"PRIVATE KEY": PrivateKey,
168 b"PUBLIC KEY": PublicKey,
169 b"ENCRYPTED PRIVATE KEY": PrivateKey,
170 b"RSA PRIVATE KEY": RSAPrivateKey,
171 b"RSA PUBLIC KEY": RSAPublicKey,
172 b"DH PARAMETERS": DHParameters,
173 b"NEW CERTIFICATE REQUEST": CertificateRequest,
174 b"CERTIFICATE REQUEST": CertificateRequest,
175 b"X509 CRL": CertificateRevocationList,
176 } # type: Dict[bytes, Type[AbstractPEMObject]]
177
178 _PEM_RE = re.compile(
179 b"-----BEGIN ("
180 + b"|".join(_PEM_TO_CLASS.keys())
181 + b""")-----\r?
182 .+?\r?
183 -----END \\1-----\r?\n?""",
184 re.DOTALL,
185 )
186
187
188 def parse(pem_str):
189 # type: (bytes) -> List[AbstractPEMObject]
190 """
191 Extract PEM objects from *pem_str*.
192
193 :param pem_str: String to parse.
194 :type pem_str: bytes
195 :return: list of :ref:`pem-objects`
196 """
197 return [
198 _PEM_TO_CLASS[match.group(1)](match.group(0))
199 for match in _PEM_RE.finditer(pem_str)
200 ]
201
202
203 def parse_file(file_name):
204 # type: (str) -> List[AbstractPEMObject]
205 """
206 Read *file_name* and parse PEM objects from it using :func:`parse`.
207 """
208 with open(file_name, "rb") as f:
209 return parse(f.read())