Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pem/_core.py: 82%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# SPDX-FileCopyrightText: 2013 Hynek Schlawack <hs@ox.cx>
2#
3# SPDX-License-Identifier: MIT
5"""
6Framework agnostic PEM file parsing functions.
7"""
9from __future__ import annotations
11import re
13from pathlib import Path
15from ._object_types import _PEM_TO_CLASS, AbstractPEMObject
18# See https://tools.ietf.org/html/rfc1421
19# and https://datatracker.ietf.org/doc/html/rfc4716 for space instead of fifth dash.
20_PEM_RE = re.compile(
21 b"----[- ]BEGIN ("
22 + b"|".join(_PEM_TO_CLASS)
23 + b""")[- ]----\r?
24(?P<payload>.+?)\r?
25----[- ]END \\1[- ]----\r?\n?""",
26 re.DOTALL,
27)
30def parse(pem_str: bytes | str) -> list[AbstractPEMObject]:
31 """
32 Extract PEM-like objects from *pem_str*.
34 Returns:
35 list[AbstractPEMObject]: list of :ref:`pem-objects`
37 .. versionchanged:: 23.1.0
38 *pem_str* can now also be a... :class:`str`.
39 """
40 return [
41 _PEM_TO_CLASS[match.group(1)](match.group(0))
42 for match in _PEM_RE.finditer(
43 pem_str if isinstance(pem_str, bytes) else pem_str.encode()
44 )
45 ]
48def parse_file(file_name: str | Path) -> list[AbstractPEMObject]:
49 """
50 Read *file_name* and parse PEM objects from it using :func:`parse`.
52 Returns:
53 list[AbstractPEMObject]: list of :ref:`pem-objects`
55 .. versionchanged:: 23.1.0
56 *file_name* can now also be a :class:`~pathlib.Path`.
57 """
58 return parse(Path(file_name).read_bytes())