Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/rsa/pem.py: 16%
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# Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
15"""Functions that load and write PEM-encoded files."""
17import base64
18import typing
20# Should either be ASCII strings or bytes.
21FlexiText = typing.Union[str, bytes]
24def _markers(pem_marker: FlexiText) -> typing.Tuple[bytes, bytes]:
25 """
26 Returns the start and end PEM markers, as bytes.
27 """
29 if not isinstance(pem_marker, bytes):
30 pem_marker = pem_marker.encode("ascii")
32 return (
33 b"-----BEGIN " + pem_marker + b"-----",
34 b"-----END " + pem_marker + b"-----",
35 )
38def _pem_lines(contents: bytes, pem_start: bytes, pem_end: bytes) -> typing.Iterator[bytes]:
39 """Generator over PEM lines between pem_start and pem_end."""
41 in_pem_part = False
42 seen_pem_start = False
44 for line in contents.splitlines():
45 line = line.strip()
47 # Skip empty lines
48 if not line:
49 continue
51 # Handle start marker
52 if line == pem_start:
53 if in_pem_part:
54 raise ValueError('Seen start marker "%r" twice' % pem_start)
56 in_pem_part = True
57 seen_pem_start = True
58 continue
60 # Skip stuff before first marker
61 if not in_pem_part:
62 continue
64 # Handle end marker
65 if in_pem_part and line == pem_end:
66 in_pem_part = False
67 break
69 # Load fields
70 if b":" in line:
71 continue
73 yield line
75 # Do some sanity checks
76 if not seen_pem_start:
77 raise ValueError('No PEM start marker "%r" found' % pem_start)
79 if in_pem_part:
80 raise ValueError('No PEM end marker "%r" found' % pem_end)
83def load_pem(contents: FlexiText, pem_marker: FlexiText) -> bytes:
84 """Loads a PEM file.
86 :param contents: the contents of the file to interpret
87 :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
88 when your file has '-----BEGIN RSA PRIVATE KEY-----' and
89 '-----END RSA PRIVATE KEY-----' markers.
91 :return: the base64-decoded content between the start and end markers.
93 @raise ValueError: when the content is invalid, for example when the start
94 marker cannot be found.
96 """
98 # We want bytes, not text. If it's text, it can be converted to ASCII bytes.
99 if not isinstance(contents, bytes):
100 contents = contents.encode("ascii")
102 (pem_start, pem_end) = _markers(pem_marker)
103 pem_lines = [line for line in _pem_lines(contents, pem_start, pem_end)]
105 # Base64-decode the contents
106 pem = b"".join(pem_lines)
107 return base64.standard_b64decode(pem)
110def save_pem(contents: bytes, pem_marker: FlexiText) -> bytes:
111 """Saves a PEM file.
113 :param contents: the contents to encode in PEM format
114 :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
115 when your file has '-----BEGIN RSA PRIVATE KEY-----' and
116 '-----END RSA PRIVATE KEY-----' markers.
118 :return: the base64-encoded content between the start and end markers, as bytes.
120 """
122 (pem_start, pem_end) = _markers(pem_marker)
124 b64 = base64.standard_b64encode(contents).replace(b"\n", b"")
125 pem_lines = [pem_start]
127 for block_start in range(0, len(b64), 64):
128 block = b64[block_start : block_start + 64]
129 pem_lines.append(block)
131 pem_lines.append(pem_end)
132 pem_lines.append(b"")
134 return b"\n".join(pem_lines)