nwo
stringlengths
10
28
sha
stringlengths
40
40
path
stringlengths
11
97
identifier
stringlengths
1
64
parameters
stringlengths
2
2.24k
return_statement
stringlengths
0
2.17k
docstring
stringlengths
0
5.45k
docstring_summary
stringlengths
0
3.83k
func_begin
int64
1
13.4k
func_end
int64
2
13.4k
function
stringlengths
28
56.4k
url
stringlengths
106
209
project
int64
1
48
executed_lines
list
executed_lines_pc
float64
0
153
missing_lines
list
missing_lines_pc
float64
0
100
covered
bool
2 classes
filecoverage
float64
2.53
100
function_lines
int64
2
1.46k
mccabe
int64
1
253
coverage
float64
0
100
docstring_lines
int64
0
112
function_nodoc
stringlengths
9
56.4k
id
int64
0
29.8k
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/xmp.py
XmpInformation.custom_properties
(self)
return self._custom_properties
Retrieve custom metadata properties defined in the undocumented pdfx metadata schema. Returns: A dictionary of key/value items for custom metadata properties.
Retrieve custom metadata properties defined in the undocumented pdfx metadata schema.
501
528
def custom_properties(self) -> Dict[Any, Any]: """ Retrieve custom metadata properties defined in the undocumented pdfx metadata schema. Returns: A dictionary of key/value items for custom metadata properties. """ if not hasattr(self, "_custom_properties"): self._custom_properties = {} for node in self.get_nodes_in_namespace("", PDFX_NAMESPACE): key = node.localName while True: # see documentation about PDFX_NAMESPACE earlier in file idx = key.find("\u2182") if idx == -1: break key = ( key[:idx] + chr(int(key[idx + 1 : idx + 5], base=16)) + key[idx + 5 :] ) if node.nodeType == node.ATTRIBUTE_NODE: value = node.nodeValue else: value = self._get_text(node) self._custom_properties[key] = value return self._custom_properties
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/xmp.py#L501-L528
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 21, 22, 24, 25, 26, 27 ]
82.142857
[ 17, 23 ]
7.142857
false
94.078947
28
6
92.857143
5
def custom_properties(self) -> Dict[Any, Any]: if not hasattr(self, "_custom_properties"): self._custom_properties = {} for node in self.get_nodes_in_namespace("", PDFX_NAMESPACE): key = node.localName while True: # see documentation about PDFX_NAMESPACE earlier in file idx = key.find("\u2182") if idx == -1: break key = ( key[:idx] + chr(int(key[idx + 1 : idx + 5], base=16)) + key[idx + 5 :] ) if node.nodeType == node.ATTRIBUTE_NODE: value = node.nodeValue else: value = self._get_text(node) self._custom_properties[key] = value return self._custom_properties
24,154
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
decompress
(data: bytes)
64
75
def decompress(data: bytes) -> bytes: try: return zlib.decompress(data) except zlib.error: d = zlib.decompressobj(zlib.MAX_WBITS | 32) result_str = b"" for b in [data[i : i + 1] for i in range(len(data))]: try: result_str += d.decompress(b) except zlib.error: pass return result_str
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L64-L75
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
94.959677
12
5
100
0
def decompress(data: bytes) -> bytes: try: return zlib.decompress(data) except zlib.error: d = zlib.decompressobj(zlib.MAX_WBITS | 32) result_str = b"" for b in [data[i : i + 1] for i in range(len(data))]: try: result_str += d.decompress(b) except zlib.error: pass return result_str
24,155
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
decode_stream_data
(stream: Any)
return data
530
567
def decode_stream_data(stream: Any) -> Union[str, bytes]: # utils.StreamObject filters = stream.get(SA.FILTER, ()) if isinstance(filters, IndirectObject): filters = cast(ArrayObject, filters.get_object()) if len(filters) and not isinstance(filters[0], NameObject): # we have a single filter instance filters = (filters,) data: bytes = stream._data # If there is not data to decode we should not try to decode the data. if data: for filter_type in filters: if filter_type in (FT.FLATE_DECODE, FTA.FL): data = FlateDecode.decode(data, stream.get(SA.DECODE_PARMS)) elif filter_type in (FT.ASCII_HEX_DECODE, FTA.AHx): data = ASCIIHexDecode.decode(data) # type: ignore elif filter_type in (FT.LZW_DECODE, FTA.LZW): data = LZWDecode.decode(data, stream.get(SA.DECODE_PARMS)) # type: ignore elif filter_type in (FT.ASCII_85_DECODE, FTA.A85): data = ASCII85Decode.decode(data) elif filter_type == FT.DCT_DECODE: data = DCTDecode.decode(data) elif filter_type == "/JPXDecode": data = JPXDecode.decode(data) elif filter_type == FT.CCITT_FAX_DECODE: height = stream.get(IA.HEIGHT, ()) data = CCITTFaxDecode.decode(data, stream.get(SA.DECODE_PARMS), height) elif filter_type == "/Crypt": decode_parms = stream.get(SA.DECODE_PARMS, {}) if "/Name" not in decode_parms and "/Type" not in decode_parms: pass else: raise NotImplementedError( "/Crypt filter with /Name or /Type not supported yet" ) else: # Unsupported filter raise NotImplementedError(f"unsupported filter {filter_type}") return data
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L530-L567
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 37 ]
83.333333
[ 14 ]
2.777778
false
94.959677
38
16
97.222222
0
def decode_stream_data(stream: Any) -> Union[str, bytes]: # utils.StreamObject filters = stream.get(SA.FILTER, ()) if isinstance(filters, IndirectObject): filters = cast(ArrayObject, filters.get_object()) if len(filters) and not isinstance(filters[0], NameObject): # we have a single filter instance filters = (filters,) data: bytes = stream._data # If there is not data to decode we should not try to decode the data. if data: for filter_type in filters: if filter_type in (FT.FLATE_DECODE, FTA.FL): data = FlateDecode.decode(data, stream.get(SA.DECODE_PARMS)) elif filter_type in (FT.ASCII_HEX_DECODE, FTA.AHx): data = ASCIIHexDecode.decode(data) # type: ignore elif filter_type in (FT.LZW_DECODE, FTA.LZW): data = LZWDecode.decode(data, stream.get(SA.DECODE_PARMS)) # type: ignore elif filter_type in (FT.ASCII_85_DECODE, FTA.A85): data = ASCII85Decode.decode(data) elif filter_type == FT.DCT_DECODE: data = DCTDecode.decode(data) elif filter_type == "/JPXDecode": data = JPXDecode.decode(data) elif filter_type == FT.CCITT_FAX_DECODE: height = stream.get(IA.HEIGHT, ()) data = CCITTFaxDecode.decode(data, stream.get(SA.DECODE_PARMS), height) elif filter_type == "/Crypt": decode_parms = stream.get(SA.DECODE_PARMS, {}) if "/Name" not in decode_parms and "/Type" not in decode_parms: pass else: raise NotImplementedError( "/Crypt filter with /Name or /Type not supported yet" ) else: # Unsupported filter raise NotImplementedError(f"unsupported filter {filter_type}") return data
24,156
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
decodeStreamData
(stream: Any)
return decode_stream_data(stream)
570
572
def decodeStreamData(stream: Any) -> Union[str, bytes]: # deprecated deprecate_with_replacement("decodeStreamData", "decode_stream_data", "4.0.0") return decode_stream_data(stream)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L570-L572
39
[]
0
[]
0
false
94.959677
3
1
100
0
def decodeStreamData(stream: Any) -> Union[str, bytes]: # deprecated deprecate_with_replacement("decodeStreamData", "decode_stream_data", "4.0.0") return decode_stream_data(stream)
24,157
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
_xobj_to_image
(x_object_obj: Dict[str, Any])
return extension, data
Users need to have the pillow package installed. It's unclear if pypdf will keep this function here, hence it's private. It might get removed at any point. Args: x_object_obj: Returns: Tuple[file extension, bytes]
Users need to have the pillow package installed.
575
666
def _xobj_to_image(x_object_obj: Dict[str, Any]) -> Tuple[Optional[str], bytes]: """ Users need to have the pillow package installed. It's unclear if pypdf will keep this function here, hence it's private. It might get removed at any point. Args: x_object_obj: Returns: Tuple[file extension, bytes] """ try: from PIL import Image except ImportError: raise ImportError( "pillow is required to do image extraction. " "It can be installed via 'pip install pypdf[image]'" ) size = (x_object_obj[IA.WIDTH], x_object_obj[IA.HEIGHT]) data = x_object_obj.get_data() # type: ignore if ( IA.COLOR_SPACE in x_object_obj and x_object_obj[IA.COLOR_SPACE] == ColorSpaces.DEVICE_RGB ): # https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes mode: Literal["RGB", "P"] = "RGB" else: mode = "P" extension = None if SA.FILTER in x_object_obj: if x_object_obj[SA.FILTER] == FT.FLATE_DECODE: extension = ".png" # mime_type = "image/png" color_space = None if "/ColorSpace" in x_object_obj: color_space = x_object_obj["/ColorSpace"].get_object() if ( isinstance(color_space, ArrayObject) and color_space[0] == "/Indexed" ): color_space, base, hival, lookup = ( value.get_object() for value in color_space ) img = Image.frombytes(mode, size, data) if color_space == "/Indexed": from .generic import ByteStringObject if isinstance(lookup, ByteStringObject): if base == ColorSpaces.DEVICE_GRAY and len(lookup) == hival + 1: lookup = b"".join( [lookup[i : i + 1] * 3 for i in range(len(lookup))] ) img.putpalette(lookup) else: img.putpalette(lookup.get_data()) img = img.convert("L" if base == ColorSpaces.DEVICE_GRAY else "RGB") if G.S_MASK in x_object_obj: # add alpha channel alpha = Image.frombytes("L", size, x_object_obj[G.S_MASK].get_data()) img.putalpha(alpha) img_byte_arr = BytesIO() img.save(img_byte_arr, format="PNG") data = img_byte_arr.getvalue() elif x_object_obj[SA.FILTER] in ( [FT.LZW_DECODE], [FT.ASCII_85_DECODE], [FT.CCITT_FAX_DECODE], ): # I'm not sure if the following logic is correct. # There might not be any relationship between the filters and the # extension if x_object_obj[SA.FILTER] in [[FT.LZW_DECODE], [FT.CCITT_FAX_DECODE]]: extension = ".tiff" # mime_type = "image/tiff" else: extension = ".png" # mime_type = "image/png" data = b_(data) elif x_object_obj[SA.FILTER] == FT.DCT_DECODE: extension = ".jpg" # mime_type = "image/jpeg" elif x_object_obj[SA.FILTER] == "/JPXDecode": extension = ".jp2" # mime_type = "image/x-jp2" elif x_object_obj[SA.FILTER] == FT.CCITT_FAX_DECODE: extension = ".tiff" # mime_type = "image/tiff" else: extension = ".png" # mime_type = "image/png" img = Image.frombytes(mode, size, data) img_byte_arr = BytesIO() img.save(img_byte_arr, format="PNG") data = img_byte_arr.getvalue() return extension, data
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L575-L666
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 54, 55, 56, 57, 58, 59, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91 ]
90.217391
[ 52, 60, 61, 73, 74, 76, 77 ]
7.608696
false
94.959677
92
20
92.391304
10
def _xobj_to_image(x_object_obj: Dict[str, Any]) -> Tuple[Optional[str], bytes]: try: from PIL import Image except ImportError: raise ImportError( "pillow is required to do image extraction. " "It can be installed via 'pip install pypdf[image]'" ) size = (x_object_obj[IA.WIDTH], x_object_obj[IA.HEIGHT]) data = x_object_obj.get_data() # type: ignore if ( IA.COLOR_SPACE in x_object_obj and x_object_obj[IA.COLOR_SPACE] == ColorSpaces.DEVICE_RGB ): # https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes mode: Literal["RGB", "P"] = "RGB" else: mode = "P" extension = None if SA.FILTER in x_object_obj: if x_object_obj[SA.FILTER] == FT.FLATE_DECODE: extension = ".png" # mime_type = "image/png" color_space = None if "/ColorSpace" in x_object_obj: color_space = x_object_obj["/ColorSpace"].get_object() if ( isinstance(color_space, ArrayObject) and color_space[0] == "/Indexed" ): color_space, base, hival, lookup = ( value.get_object() for value in color_space ) img = Image.frombytes(mode, size, data) if color_space == "/Indexed": from .generic import ByteStringObject if isinstance(lookup, ByteStringObject): if base == ColorSpaces.DEVICE_GRAY and len(lookup) == hival + 1: lookup = b"".join( [lookup[i : i + 1] * 3 for i in range(len(lookup))] ) img.putpalette(lookup) else: img.putpalette(lookup.get_data()) img = img.convert("L" if base == ColorSpaces.DEVICE_GRAY else "RGB") if G.S_MASK in x_object_obj: # add alpha channel alpha = Image.frombytes("L", size, x_object_obj[G.S_MASK].get_data()) img.putalpha(alpha) img_byte_arr = BytesIO() img.save(img_byte_arr, format="PNG") data = img_byte_arr.getvalue() elif x_object_obj[SA.FILTER] in ( [FT.LZW_DECODE], [FT.ASCII_85_DECODE], [FT.CCITT_FAX_DECODE], ): # I'm not sure if the following logic is correct. # There might not be any relationship between the filters and the # extension if x_object_obj[SA.FILTER] in [[FT.LZW_DECODE], [FT.CCITT_FAX_DECODE]]: extension = ".tiff" # mime_type = "image/tiff" else: extension = ".png" # mime_type = "image/png" data = b_(data) elif x_object_obj[SA.FILTER] == FT.DCT_DECODE: extension = ".jpg" # mime_type = "image/jpeg" elif x_object_obj[SA.FILTER] == "/JPXDecode": extension = ".jp2" # mime_type = "image/x-jp2" elif x_object_obj[SA.FILTER] == FT.CCITT_FAX_DECODE: extension = ".tiff" # mime_type = "image/tiff" else: extension = ".png" # mime_type = "image/png" img = Image.frombytes(mode, size, data) img_byte_arr = BytesIO() img.save(img_byte_arr, format="PNG") data = img_byte_arr.getvalue() return extension, data
24,158
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
FlateDecode.decode
( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, )
return str_data
Decode data which is flate-encoded. Args: data: flate-encoded data. decode_parms: a dictionary of values, understanding the "/Predictor":<int> key only Returns: The flate-decoded data. Raises: PdfReadError:
Decode data which is flate-encoded.
80
149
def decode( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, ) -> bytes: """ Decode data which is flate-encoded. Args: data: flate-encoded data. decode_parms: a dictionary of values, understanding the "/Predictor":<int> key only Returns: The flate-decoded data. Raises: PdfReadError: """ if "decodeParms" in kwargs: # deprecated deprecate_with_replacement("decodeParms", "parameters", "4.0.0") decode_parms = kwargs["decodeParms"] str_data = decompress(data) predictor = 1 if decode_parms: try: if isinstance(decode_parms, ArrayObject): for decode_parm in decode_parms: if "/Predictor" in decode_parm: predictor = decode_parm["/Predictor"] else: predictor = decode_parms.get("/Predictor", 1) except (AttributeError, TypeError): # Type Error is NullObject pass # Usually an array with a null object was read # predictor 1 == no predictor if predictor != 1: # The /Columns param. has 1 as the default value; see ISO 32000, # §7.4.4.3 LZWDecode and FlateDecode Parameters, Table 8 DEFAULT_BITS_PER_COMPONENT = 8 if isinstance(decode_parms, ArrayObject): columns = 1 bits_per_component = DEFAULT_BITS_PER_COMPONENT for decode_parm in decode_parms: if "/Columns" in decode_parm: columns = decode_parm["/Columns"] if LZW.BITS_PER_COMPONENT in decode_parm: bits_per_component = decode_parm[LZW.BITS_PER_COMPONENT] else: columns = ( 1 if decode_parms is None else decode_parms.get(LZW.COLUMNS, 1) ) bits_per_component = ( decode_parms.get(LZW.BITS_PER_COMPONENT, DEFAULT_BITS_PER_COMPONENT) if decode_parms else DEFAULT_BITS_PER_COMPONENT ) # PNG predictor can vary by row and so is the lead byte on each row rowlength = ( math.ceil(columns * bits_per_component / 8) + 1 ) # number of bytes # PNG prediction: if 10 <= predictor <= 15: str_data = FlateDecode._decode_png_prediction(str_data, columns, rowlength) # type: ignore else: # unsupported predictor raise PdfReadError(f"Unsupported flatedecode predictor {predictor!r}") return str_data
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L80-L149
39
[ 0, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 49, 52, 58, 59, 63, 64, 65, 67, 68, 69 ]
52.238806
[ 47 ]
1.492537
false
94.959677
70
13
98.507463
12
def decode( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, ) -> bytes: if "decodeParms" in kwargs: # deprecated deprecate_with_replacement("decodeParms", "parameters", "4.0.0") decode_parms = kwargs["decodeParms"] str_data = decompress(data) predictor = 1 if decode_parms: try: if isinstance(decode_parms, ArrayObject): for decode_parm in decode_parms: if "/Predictor" in decode_parm: predictor = decode_parm["/Predictor"] else: predictor = decode_parms.get("/Predictor", 1) except (AttributeError, TypeError): # Type Error is NullObject pass # Usually an array with a null object was read # predictor 1 == no predictor if predictor != 1: # The /Columns param. has 1 as the default value; see ISO 32000, # §7.4.4.3 LZWDecode and FlateDecode Parameters, Table 8 DEFAULT_BITS_PER_COMPONENT = 8 if isinstance(decode_parms, ArrayObject): columns = 1 bits_per_component = DEFAULT_BITS_PER_COMPONENT for decode_parm in decode_parms: if "/Columns" in decode_parm: columns = decode_parm["/Columns"] if LZW.BITS_PER_COMPONENT in decode_parm: bits_per_component = decode_parm[LZW.BITS_PER_COMPONENT] else: columns = ( 1 if decode_parms is None else decode_parms.get(LZW.COLUMNS, 1) ) bits_per_component = ( decode_parms.get(LZW.BITS_PER_COMPONENT, DEFAULT_BITS_PER_COMPONENT) if decode_parms else DEFAULT_BITS_PER_COMPONENT ) # PNG predictor can vary by row and so is the lead byte on each row rowlength = ( math.ceil(columns * bits_per_component / 8) + 1 ) # number of bytes # PNG prediction: if 10 <= predictor <= 15: str_data = FlateDecode._decode_png_prediction(str_data, columns, rowlength) # type: ignore else: # unsupported predictor raise PdfReadError(f"Unsupported flatedecode predictor {predictor!r}") return str_data
24,159
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
FlateDecode._decode_png_prediction
(data: str, columns: int, rowlength: int)
return output.getvalue()
152
189
def _decode_png_prediction(data: str, columns: int, rowlength: int) -> bytes: output = BytesIO() # PNG prediction can vary from row to row if len(data) % rowlength != 0: raise PdfReadError("Image data is not rectangular") prev_rowdata = (0,) * rowlength for row in range(len(data) // rowlength): rowdata = [ ord_(x) for x in data[(row * rowlength) : ((row + 1) * rowlength)] ] filter_byte = rowdata[0] if filter_byte == 0: pass elif filter_byte == 1: for i in range(2, rowlength): rowdata[i] = (rowdata[i] + rowdata[i - 1]) % 256 elif filter_byte == 2: for i in range(1, rowlength): rowdata[i] = (rowdata[i] + prev_rowdata[i]) % 256 elif filter_byte == 3: for i in range(1, rowlength): left = rowdata[i - 1] if i > 1 else 0 floor = math.floor(left + prev_rowdata[i]) / 2 rowdata[i] = (rowdata[i] + int(floor)) % 256 elif filter_byte == 4: for i in range(1, rowlength): left = rowdata[i - 1] if i > 1 else 0 up = prev_rowdata[i] up_left = prev_rowdata[i - 1] if i > 1 else 0 paeth = paeth_predictor(left, up, up_left) rowdata[i] = (rowdata[i] + paeth) % 256 else: # unsupported PNG filter raise PdfReadError(f"Unsupported PNG filter {filter_byte!r}") prev_rowdata = tuple(rowdata) output.write(bytearray(rowdata[1:])) return output.getvalue()
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L152-L189
39
[ 0, 1, 2, 3, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 35, 36, 37 ]
84.210526
[ 4, 34 ]
5.263158
false
94.959677
38
13
94.736842
0
def _decode_png_prediction(data: str, columns: int, rowlength: int) -> bytes: output = BytesIO() # PNG prediction can vary from row to row if len(data) % rowlength != 0: raise PdfReadError("Image data is not rectangular") prev_rowdata = (0,) * rowlength for row in range(len(data) // rowlength): rowdata = [ ord_(x) for x in data[(row * rowlength) : ((row + 1) * rowlength)] ] filter_byte = rowdata[0] if filter_byte == 0: pass elif filter_byte == 1: for i in range(2, rowlength): rowdata[i] = (rowdata[i] + rowdata[i - 1]) % 256 elif filter_byte == 2: for i in range(1, rowlength): rowdata[i] = (rowdata[i] + prev_rowdata[i]) % 256 elif filter_byte == 3: for i in range(1, rowlength): left = rowdata[i - 1] if i > 1 else 0 floor = math.floor(left + prev_rowdata[i]) / 2 rowdata[i] = (rowdata[i] + int(floor)) % 256 elif filter_byte == 4: for i in range(1, rowlength): left = rowdata[i - 1] if i > 1 else 0 up = prev_rowdata[i] up_left = prev_rowdata[i - 1] if i > 1 else 0 paeth = paeth_predictor(left, up, up_left) rowdata[i] = (rowdata[i] + paeth) % 256 else: # unsupported PNG filter raise PdfReadError(f"Unsupported PNG filter {filter_byte!r}") prev_rowdata = tuple(rowdata) output.write(bytearray(rowdata[1:])) return output.getvalue()
24,160
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
FlateDecode.encode
(data: bytes)
return zlib.compress(data)
192
193
def encode(data: bytes) -> bytes: return zlib.compress(data)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L192-L193
39
[ 0, 1 ]
100
[]
0
true
94.959677
2
1
100
0
def encode(data: bytes) -> bytes: return zlib.compress(data)
24,161
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
ASCIIHexDecode.decode
( data: str, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, # noqa: F841 **kwargs: Any, )
return retval
Decode an ASCII-Hex encoded data stream. Args: data: a str sequence of hexadecimal-encoded values to be converted into a base-7 ASCII string decode_parms: a string conversion in base-7 ASCII, where each of its values v is such that 0 <= ord(v) <= 127. Returns: A string conversion in base-7 ASCII, where each of its values v is such that 0 <= ord(v) <= 127. Raises: PdfStreamError:
Decode an ASCII-Hex encoded data stream.
203
245
def decode( data: str, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, # noqa: F841 **kwargs: Any, ) -> str: """ Decode an ASCII-Hex encoded data stream. Args: data: a str sequence of hexadecimal-encoded values to be converted into a base-7 ASCII string decode_parms: a string conversion in base-7 ASCII, where each of its values v is such that 0 <= ord(v) <= 127. Returns: A string conversion in base-7 ASCII, where each of its values v is such that 0 <= ord(v) <= 127. Raises: PdfStreamError: """ if "decodeParms" in kwargs: # deprecated deprecate_with_replacement("decodeParms", "parameters", "4.0.0") decode_parms = kwargs["decodeParms"] # noqa: F841 retval = "" hex_pair = "" index = 0 while True: if index >= len(data): raise PdfStreamError("Unexpected EOD in ASCIIHexDecode") char = data[index] if char == ">": break elif char.isspace(): index += 1 continue hex_pair += char if len(hex_pair) == 2: retval += chr(int(hex_pair, base=16)) hex_pair = "" index += 1 assert hex_pair == "" return retval
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L203-L245
39
[ 0, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 ]
50
[]
0
false
94.959677
43
8
100
14
def decode( data: str, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, # noqa: F841 **kwargs: Any, ) -> str: if "decodeParms" in kwargs: # deprecated deprecate_with_replacement("decodeParms", "parameters", "4.0.0") decode_parms = kwargs["decodeParms"] # noqa: F841 retval = "" hex_pair = "" index = 0 while True: if index >= len(data): raise PdfStreamError("Unexpected EOD in ASCIIHexDecode") char = data[index] if char == ">": break elif char.isspace(): index += 1 continue hex_pair += char if len(hex_pair) == 2: retval += chr(int(hex_pair, base=16)) hex_pair = "" index += 1 assert hex_pair == "" return retval
24,162
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
LZWDecode.decode
( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, )
return LZWDecode.Decoder(data).decode()
Decode an LZW encoded data stream. Args: data: bytes`` or ``str`` text to decode. decode_parms: a dictionary of parameter values. Returns: decoded data.
Decode an LZW encoded data stream.
333
351
def decode( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, ) -> str: """ Decode an LZW encoded data stream. Args: data: bytes`` or ``str`` text to decode. decode_parms: a dictionary of parameter values. Returns: decoded data. """ if "decodeParms" in kwargs: # deprecated deprecate_with_replacement("decodeParms", "parameters", "4.0.0") decode_parms = kwargs["decodeParms"] # noqa: F841 return LZWDecode.Decoder(data).decode()
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L333-L351
39
[ 0, 18 ]
12.5
[]
0
false
94.959677
19
2
100
8
def decode( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, ) -> str: if "decodeParms" in kwargs: # deprecated deprecate_with_replacement("decodeParms", "parameters", "4.0.0") decode_parms = kwargs["decodeParms"] # noqa: F841 return LZWDecode.Decoder(data).decode()
24,163
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
ASCII85Decode.decode
( data: Union[str, bytes], decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, )
return bytes(out)
358
386
def decode( data: Union[str, bytes], decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, ) -> bytes: if "decodeParms" in kwargs: # deprecated deprecate_with_replacement("decodeParms", "parameters", "4.0.0") decode_parms = kwargs["decodeParms"] # noqa: F841 if isinstance(data, str): data = data.encode("ascii") group_index = b = 0 out = bytearray() for char in data: if ord("!") <= char and char <= ord("u"): group_index += 1 b = b * 85 + (char - 33) if group_index == 5: out += struct.pack(b">L", b) group_index = b = 0 elif char == ord("z"): assert group_index == 0 out += b"\0\0\0\0" elif char == ord("~"): if group_index: for _ in range(5 - group_index): b = b * 85 + 84 out += struct.pack(b">L", b)[: group_index - 1] break return bytes(out)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L358-L386
39
[ 0, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28 ]
84.615385
[]
0
false
94.959677
29
12
100
0
def decode( data: Union[str, bytes], decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, ) -> bytes: if "decodeParms" in kwargs: # deprecated deprecate_with_replacement("decodeParms", "parameters", "4.0.0") decode_parms = kwargs["decodeParms"] # noqa: F841 if isinstance(data, str): data = data.encode("ascii") group_index = b = 0 out = bytearray() for char in data: if ord("!") <= char and char <= ord("u"): group_index += 1 b = b * 85 + (char - 33) if group_index == 5: out += struct.pack(b">L", b) group_index = b = 0 elif char == ord("z"): assert group_index == 0 out += b"\0\0\0\0" elif char == ord("~"): if group_index: for _ in range(5 - group_index): b = b * 85 + 84 out += struct.pack(b">L", b)[: group_index - 1] break return bytes(out)
24,164
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
DCTDecode.decode
( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, )
return data
391
399
def decode( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, ) -> bytes: if "decodeParms" in kwargs: # deprecated deprecate_with_replacement("decodeParms", "parameters", "4.0.0") decode_parms = kwargs["decodeParms"] # noqa: F841 return data
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L391-L399
39
[ 0, 8 ]
33.333333
[]
0
false
94.959677
9
2
100
0
def decode( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, ) -> bytes: if "decodeParms" in kwargs: # deprecated deprecate_with_replacement("decodeParms", "parameters", "4.0.0") decode_parms = kwargs["decodeParms"] # noqa: F841 return data
24,165
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
JPXDecode.decode
( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, )
return data
404
412
def decode( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, ) -> bytes: if "decodeParms" in kwargs: # deprecated deprecate_with_replacement("decodeParms", "parameters", "4.0.0") decode_parms = kwargs["decodeParms"] # noqa: F841 return data
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L404-L412
39
[ 0, 8 ]
33.333333
[]
0
false
94.959677
9
2
100
0
def decode( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, **kwargs: Any, ) -> bytes: if "decodeParms" in kwargs: # deprecated deprecate_with_replacement("decodeParms", "parameters", "4.0.0") decode_parms = kwargs["decodeParms"] # noqa: F841 return data
24,166
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
CCITParameters.__init__
(self, K: int = 0, columns: int = 0, rows: int = 0)
418
425
def __init__(self, K: int = 0, columns: int = 0, rows: int = 0) -> None: self.K = K self.EndOfBlock = None self.EndOfLine = None self.EncodedByteAlign = None self.columns = columns # width self.rows = rows # height self.DamagedRowsBeforeError = None
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L418-L425
39
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
94.959677
8
1
100
0
def __init__(self, K: int = 0, columns: int = 0, rows: int = 0) -> None: self.K = K self.EndOfBlock = None self.EndOfLine = None self.EncodedByteAlign = None self.columns = columns # width self.rows = rows # height self.DamagedRowsBeforeError = None
24,167
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
CCITParameters.group
(self)
return CCITTgroup
428
435
def group(self) -> int: if self.K < 0: CCITTgroup = 4 else: # k == 0: Pure one-dimensional encoding (Group 3, 1-D) # k > 0: Mixed one- and two-dimensional encoding (Group 3, 2-D) CCITTgroup = 3 return CCITTgroup
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L428-L435
39
[ 0, 1, 2, 5, 6, 7 ]
75
[]
0
false
94.959677
8
2
100
0
def group(self) -> int: if self.K < 0: CCITTgroup = 4 else: # k == 0: Pure one-dimensional encoding (Group 3, 1-D) # k > 0: Mixed one- and two-dimensional encoding (Group 3, 2-D) CCITTgroup = 3 return CCITTgroup
24,168
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
CCITTFaxDecode._get_parameters
( parameters: Union[None, ArrayObject, DictionaryObject], rows: int )
return CCITParameters(k, columns, rows)
449
468
def _get_parameters( parameters: Union[None, ArrayObject, DictionaryObject], rows: int ) -> CCITParameters: # TABLE 3.9 Optional parameters for the CCITTFaxDecode filter k = 0 columns = 1728 if parameters: if isinstance(parameters, ArrayObject): for decode_parm in parameters: if CCITT.COLUMNS in decode_parm: columns = decode_parm[CCITT.COLUMNS] if CCITT.K in decode_parm: k = decode_parm[CCITT.K] else: if CCITT.COLUMNS in parameters: columns = parameters[CCITT.COLUMNS] # type: ignore if CCITT.K in parameters: k = parameters[CCITT.K] # type: ignore return CCITParameters(k, columns, rows)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L449-L468
39
[ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19 ]
85
[]
0
false
94.959677
20
8
100
0
def _get_parameters( parameters: Union[None, ArrayObject, DictionaryObject], rows: int ) -> CCITParameters: # TABLE 3.9 Optional parameters for the CCITTFaxDecode filter k = 0 columns = 1728 if parameters: if isinstance(parameters, ArrayObject): for decode_parm in parameters: if CCITT.COLUMNS in decode_parm: columns = decode_parm[CCITT.COLUMNS] if CCITT.K in decode_parm: k = decode_parm[CCITT.K] else: if CCITT.COLUMNS in parameters: columns = parameters[CCITT.COLUMNS] # type: ignore if CCITT.K in parameters: k = parameters[CCITT.K] # type: ignore return CCITParameters(k, columns, rows)
24,169
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/filters.py
CCITTFaxDecode.decode
( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, height: int = 0, **kwargs: Any, )
return tiff_header + data
471
527
def decode( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, height: int = 0, **kwargs: Any, ) -> bytes: if "decodeParms" in kwargs: # deprecated deprecate_with_replacement("decodeParms", "parameters", "4.0.0") decode_parms = kwargs["decodeParms"] parms = CCITTFaxDecode._get_parameters(decode_parms, height) img_size = len(data) tiff_header_struct = "<2shlh" + "hhll" * 8 + "h" tiff_header = struct.pack( tiff_header_struct, b"II", # Byte order indication: Little endian 42, # Version number (always 42) 8, # Offset to first IFD 8, # Number of tags in IFD 256, 4, 1, parms.columns, # ImageWidth, LONG, 1, width 257, 4, 1, parms.rows, # ImageLength, LONG, 1, length 258, 3, 1, 1, # BitsPerSample, SHORT, 1, 1 259, 3, 1, parms.group, # Compression, SHORT, 1, 4 = CCITT Group 4 fax encoding 262, 3, 1, 0, # Thresholding, SHORT, 1, 0 = WhiteIsZero 273, 4, 1, struct.calcsize( tiff_header_struct ), # StripOffsets, LONG, 1, length of header 278, 4, 1, parms.rows, # RowsPerStrip, LONG, 1, length 279, 4, 1, img_size, # StripByteCounts, LONG, 1, size of image 0, # last IFD ) return tiff_header + data
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/filters.py#L471-L527
39
[ 0, 9, 10, 11, 12, 13, 55, 56 ]
14.814815
[]
0
false
94.959677
57
2
100
0
def decode( data: bytes, decode_parms: Union[None, ArrayObject, DictionaryObject] = None, height: int = 0, **kwargs: Any, ) -> bytes: if "decodeParms" in kwargs: # deprecated deprecate_with_replacement("decodeParms", "parameters", "4.0.0") decode_parms = kwargs["decodeParms"] parms = CCITTFaxDecode._get_parameters(decode_parms, height) img_size = len(data) tiff_header_struct = "<2shlh" + "hhll" * 8 + "h" tiff_header = struct.pack( tiff_header_struct, b"II", # Byte order indication: Little endian 42, # Version number (always 42) 8, # Offset to first IFD 8, # Number of tags in IFD 256, 4, 1, parms.columns, # ImageWidth, LONG, 1, width 257, 4, 1, parms.rows, # ImageLength, LONG, 1, length 258, 3, 1, 1, # BitsPerSample, SHORT, 1, 1 259, 3, 1, parms.group, # Compression, SHORT, 1, 4 = CCITT Group 4 fax encoding 262, 3, 1, 0, # Thresholding, SHORT, 1, 0 = WhiteIsZero 273, 4, 1, struct.calcsize( tiff_header_struct ), # StripOffsets, LONG, 1, length of header 278, 4, 1, parms.rows, # RowsPerStrip, LONG, 1, length 279, 4, 1, img_size, # StripByteCounts, LONG, 1, size of image 0, # last IFD ) return tiff_header + data
24,170
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_protocols.py
PdfObjectProtocol.clone
( self, pdf_dest: Any, force_duplicate: bool = False, ignore_fields: Union[Tuple[str, ...], List[str], None] = (), )
18
24
def clone( self, pdf_dest: Any, force_duplicate: bool = False, ignore_fields: Union[Tuple[str, ...], List[str], None] = (), ) -> Any: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_protocols.py#L18-L24
39
[ 0 ]
14.285714
[ 6 ]
14.285714
false
66.666667
7
1
85.714286
0
def clone( self, pdf_dest: Any, force_duplicate: bool = False, ignore_fields: Union[Tuple[str, ...], List[str], None] = (), ) -> Any: ...
24,171
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_protocols.py
PdfObjectProtocol._reference_clone
(self, clone: Any, pdf_dest: Any)
26
27
def _reference_clone(self, clone: Any, pdf_dest: Any) -> Any: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_protocols.py#L26-L27
39
[ 0 ]
50
[ 1 ]
50
false
66.666667
2
1
50
0
def _reference_clone(self, clone: Any, pdf_dest: Any) -> Any: ...
24,172
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_protocols.py
PdfObjectProtocol.get_object
(self)
29
30
def get_object(self) -> Optional["PdfObjectProtocol"]: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_protocols.py#L29-L30
39
[ 0 ]
50
[ 1 ]
50
false
66.666667
2
1
50
0
def get_object(self) -> Optional["PdfObjectProtocol"]: ...
24,173
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_protocols.py
PdfReaderProtocol.pdf_header
(self)
35
36
def pdf_header(self) -> str: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_protocols.py#L35-L36
39
[]
0
[]
0
false
66.666667
2
1
100
0
def pdf_header(self) -> str: ...
24,174
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_protocols.py
PdfReaderProtocol.strict
(self)
39
40
def strict(self) -> bool: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_protocols.py#L39-L40
39
[]
0
[]
0
false
66.666667
2
1
100
0
def strict(self) -> bool: ...
24,175
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_protocols.py
PdfReaderProtocol.xref
(self)
43
44
def xref(self) -> Dict[int, Dict[int, Any]]: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_protocols.py#L43-L44
39
[]
0
[]
0
false
66.666667
2
1
100
0
def xref(self) -> Dict[int, Dict[int, Any]]: ...
24,176
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_protocols.py
PdfReaderProtocol.pages
(self)
47
48
def pages(self) -> List[Any]: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_protocols.py#L47-L48
39
[]
0
[]
0
false
66.666667
2
1
100
0
def pages(self) -> List[Any]: ...
24,177
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_protocols.py
PdfReaderProtocol.trailer
(self)
51
52
def trailer(self) -> Dict[str, Any]: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_protocols.py#L51-L52
39
[]
0
[]
0
false
66.666667
2
1
100
0
def trailer(self) -> Dict[str, Any]: ...
24,178
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_protocols.py
PdfReaderProtocol.get_object
(self, indirect_reference: Any)
54
55
def get_object(self, indirect_reference: Any) -> Optional[PdfObjectProtocol]: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_protocols.py#L54-L55
39
[]
0
[]
0
false
66.666667
2
1
100
0
def get_object(self, indirect_reference: Any) -> Optional[PdfObjectProtocol]: ...
24,179
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_protocols.py
PdfWriterProtocol.get_object
(self, indirect_reference: Any)
62
63
def get_object(self, indirect_reference: Any) -> Optional[PdfObjectProtocol]: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_protocols.py#L62-L63
39
[]
0
[]
0
false
66.666667
2
1
100
0
def get_object(self, indirect_reference: Any) -> Optional[PdfObjectProtocol]: ...
24,180
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_protocols.py
PdfWriterProtocol.write
(self, stream: Union[Path, StrByteType])
65
66
def write(self, stream: Union[Path, StrByteType]) -> Tuple[bool, IO]: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_protocols.py#L65-L66
39
[]
0
[]
0
false
66.666667
2
1
100
0
def write(self, stream: Union[Path, StrByteType]) -> Tuple[bool, IO]: ...
24,181
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_security.py
_alg32
( password: str, rev: Literal[2, 3, 4], keylen: int, owner_entry: ByteStringObject, p_entry: int, id1_entry: ByteStringObject, metadata_encrypt: bool = True, )
return md5_hash[:keylen]
Implementation of algorithm 3.2 of the PDF standard security handler. See section 3.5.2 of the PDF 1.6 reference. Args: password: The encryption secret as a bytes-string rev: The encryption revision (see PDF standard) keylen: owner_entry: p_entry: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. id1_entry: metadata_encrypt: (Default value = True) Returns: An MD5 hash of keylen characters.
Implementation of algorithm 3.2 of the PDF standard security handler.
54
121
def _alg32( password: str, rev: Literal[2, 3, 4], keylen: int, owner_entry: ByteStringObject, p_entry: int, id1_entry: ByteStringObject, metadata_encrypt: bool = True, ) -> bytes: """ Implementation of algorithm 3.2 of the PDF standard security handler. See section 3.5.2 of the PDF 1.6 reference. Args: password: The encryption secret as a bytes-string rev: The encryption revision (see PDF standard) keylen: owner_entry: p_entry: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. id1_entry: metadata_encrypt: (Default value = True) Returns: An MD5 hash of keylen characters. """ # 1. Pad or truncate the password string to exactly 32 bytes. If the # password string is more than 32 bytes long, use only its first 32 bytes; # if it is less than 32 bytes long, pad it by appending the required number # of additional bytes from the beginning of the padding string # (_encryption_padding). password_bytes = b_((str_(password) + str_(_encryption_padding))[:32]) # 2. Initialize the MD5 hash function and pass the result of step 1 as # input to this function. m = md5(password_bytes) # 3. Pass the value of the encryption dictionary's /O entry to the MD5 hash # function. m.update(owner_entry.original_bytes) # 4. Treat the value of the /P entry as an unsigned 4-byte integer and pass # these bytes to the MD5 hash function, low-order byte first. p_entry_bytes = struct.pack("<i", p_entry) m.update(p_entry_bytes) # 5. Pass the first element of the file's file identifier array to the MD5 # hash function. m.update(id1_entry.original_bytes) # 6. (Revision 3 or greater) If document metadata is not being encrypted, # pass 4 bytes with the value 0xFFFFFFFF to the MD5 hash function. if rev >= 3 and not metadata_encrypt: m.update(b"\xff\xff\xff\xff") # 7. Finish the hash. md5_hash = m.digest() # 8. (Revision 3 or greater) Do the following 50 times: Take the output # from the previous MD5 hash and pass the first n bytes of the output as # input into a new MD5 hash, where n is the number of bytes of the # encryption key as defined by the value of the encryption dictionary's # /Length entry. if rev >= 3: for _ in range(50): md5_hash = md5(md5_hash[:keylen]).digest() # 9. Set the encryption key to the first n bytes of the output from the # final MD5 hash, where n is always 5 for revision 2 but, for revision 3 or # greater, depends on the value of the encryption dictionary's /Length # entry. return md5_hash[:keylen]
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_security.py#L54-L121
39
[ 0, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67 ]
51.470588
[]
0
false
98.019802
68
5
100
19
def _alg32( password: str, rev: Literal[2, 3, 4], keylen: int, owner_entry: ByteStringObject, p_entry: int, id1_entry: ByteStringObject, metadata_encrypt: bool = True, ) -> bytes: # 1. Pad or truncate the password string to exactly 32 bytes. If the # password string is more than 32 bytes long, use only its first 32 bytes; # if it is less than 32 bytes long, pad it by appending the required number # of additional bytes from the beginning of the padding string # (_encryption_padding). password_bytes = b_((str_(password) + str_(_encryption_padding))[:32]) # 2. Initialize the MD5 hash function and pass the result of step 1 as # input to this function. m = md5(password_bytes) # 3. Pass the value of the encryption dictionary's /O entry to the MD5 hash # function. m.update(owner_entry.original_bytes) # 4. Treat the value of the /P entry as an unsigned 4-byte integer and pass # these bytes to the MD5 hash function, low-order byte first. p_entry_bytes = struct.pack("<i", p_entry) m.update(p_entry_bytes) # 5. Pass the first element of the file's file identifier array to the MD5 # hash function. m.update(id1_entry.original_bytes) # 6. (Revision 3 or greater) If document metadata is not being encrypted, # pass 4 bytes with the value 0xFFFFFFFF to the MD5 hash function. if rev >= 3 and not metadata_encrypt: m.update(b"\xff\xff\xff\xff") # 7. Finish the hash. md5_hash = m.digest() # 8. (Revision 3 or greater) Do the following 50 times: Take the output # from the previous MD5 hash and pass the first n bytes of the output as # input into a new MD5 hash, where n is the number of bytes of the # encryption key as defined by the value of the encryption dictionary's # /Length entry. if rev >= 3: for _ in range(50): md5_hash = md5(md5_hash[:keylen]).digest() # 9. Set the encryption key to the first n bytes of the output from the # final MD5 hash, where n is always 5 for revision 2 but, for revision 3 or # greater, depends on the value of the encryption dictionary's /Length # entry. return md5_hash[:keylen]
24,182
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_security.py
_alg33
( owner_password: str, user_password: str, rev: Literal[2, 3, 4], keylen: int )
return val
Implementation of algorithm 3.3 of the PDF standard security handler, section 3.5.2 of the PDF 1.6 reference. Args: owner_password: user_password: rev: The encryption revision (see PDF standard) keylen: Returns: A transformed version of the owner and the user password
Implementation of algorithm 3.3 of the PDF standard security handler, section 3.5.2 of the PDF 1.6 reference.
124
160
def _alg33( owner_password: str, user_password: str, rev: Literal[2, 3, 4], keylen: int ) -> bytes: """ Implementation of algorithm 3.3 of the PDF standard security handler, section 3.5.2 of the PDF 1.6 reference. Args: owner_password: user_password: rev: The encryption revision (see PDF standard) keylen: Returns: A transformed version of the owner and the user password """ # steps 1 - 4 key = _alg33_1(owner_password, rev, keylen) # 5. Pad or truncate the user password string as described in step 1 of # algorithm 3.2. user_password_bytes = b_((user_password + str_(_encryption_padding))[:32]) # 6. Encrypt the result of step 5, using an RC4 encryption function with # the encryption key obtained in step 4. val = RC4_encrypt(key, user_password_bytes) # 7. (Revision 3 or greater) Do the following 19 times: Take the output # from the previous invocation of the RC4 function and pass it as input to # a new invocation of the function; use an encryption key generated by # taking each byte of the encryption key obtained in step 4 and performing # an XOR operation between that byte and the single-byte value of the # iteration counter (from 1 to 19). if rev >= 3: for i in range(1, 20): new_key = "".join(chr(ord_(key_char) ^ i) for key_char in key) val = RC4_encrypt(new_key, val) # 8. Store the output from the final invocation of the RC4 as the value of # the /O entry in the encryption dictionary. return val
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_security.py#L124-L160
39
[ 0, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36 ]
59.459459
[]
0
false
98.019802
37
3
100
11
def _alg33( owner_password: str, user_password: str, rev: Literal[2, 3, 4], keylen: int ) -> bytes: # steps 1 - 4 key = _alg33_1(owner_password, rev, keylen) # 5. Pad or truncate the user password string as described in step 1 of # algorithm 3.2. user_password_bytes = b_((user_password + str_(_encryption_padding))[:32]) # 6. Encrypt the result of step 5, using an RC4 encryption function with # the encryption key obtained in step 4. val = RC4_encrypt(key, user_password_bytes) # 7. (Revision 3 or greater) Do the following 19 times: Take the output # from the previous invocation of the RC4 function and pass it as input to # a new invocation of the function; use an encryption key generated by # taking each byte of the encryption key obtained in step 4 and performing # an XOR operation between that byte and the single-byte value of the # iteration counter (from 1 to 19). if rev >= 3: for i in range(1, 20): new_key = "".join(chr(ord_(key_char) ^ i) for key_char in key) val = RC4_encrypt(new_key, val) # 8. Store the output from the final invocation of the RC4 as the value of # the /O entry in the encryption dictionary. return val
24,183
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_security.py
_alg33_1
(password: str, rev: Literal[2, 3, 4], keylen: int)
return key
Steps 1-4 of algorithm 3.3 Args: password: rev: The encryption revision (see PDF standard) keylen: Returns: A transformed version of the password
Steps 1-4 of algorithm 3.3
163
193
def _alg33_1(password: str, rev: Literal[2, 3, 4], keylen: int) -> bytes: """ Steps 1-4 of algorithm 3.3 Args: password: rev: The encryption revision (see PDF standard) keylen: Returns: A transformed version of the password """ # 1. Pad or truncate the owner password string as described in step 1 of # algorithm 3.2. If there is no owner password, use the user password # instead. password_bytes = b_((password + str_(_encryption_padding))[:32]) # 2. Initialize the MD5 hash function and pass the result of step 1 as # input to this function. m = md5(password_bytes) # 3. (Revision 3 or greater) Do the following 50 times: Take the output # from the previous MD5 hash and pass it as input into a new MD5 hash. md5_hash = m.digest() if rev >= 3: for _ in range(50): md5_hash = md5(md5_hash).digest() # 4. Create an RC4 encryption key using the first n bytes of the output # from the final MD5 hash, where n is always 5 for revision 2 but, for # revision 3 or greater, depends on the value of the encryption # dictionary's /Length entry. key = md5_hash[:keylen] return key
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_security.py#L163-L193
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 ]
100
[]
0
true
98.019802
31
3
100
9
def _alg33_1(password: str, rev: Literal[2, 3, 4], keylen: int) -> bytes: # 1. Pad or truncate the owner password string as described in step 1 of # algorithm 3.2. If there is no owner password, use the user password # instead. password_bytes = b_((password + str_(_encryption_padding))[:32]) # 2. Initialize the MD5 hash function and pass the result of step 1 as # input to this function. m = md5(password_bytes) # 3. (Revision 3 or greater) Do the following 50 times: Take the output # from the previous MD5 hash and pass it as input into a new MD5 hash. md5_hash = m.digest() if rev >= 3: for _ in range(50): md5_hash = md5(md5_hash).digest() # 4. Create an RC4 encryption key using the first n bytes of the output # from the final MD5 hash, where n is always 5 for revision 2 but, for # revision 3 or greater, depends on the value of the encryption # dictionary's /Length entry. key = md5_hash[:keylen] return key
24,184
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_security.py
_alg34
( password: str, owner_entry: ByteStringObject, p_entry: int, id1_entry: ByteStringObject, )
return U, key
Implementation of algorithm 3.4 of the PDF standard security handler. See section 3.5.2 of the PDF 1.6 reference. Args: password: owner_entry: p_entry: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. id1_entry: Returns: A Tuple (u-value, key)
Implementation of algorithm 3.4 of the PDF standard security handler.
196
231
def _alg34( password: str, owner_entry: ByteStringObject, p_entry: int, id1_entry: ByteStringObject, ) -> Tuple[bytes, bytes]: """ Implementation of algorithm 3.4 of the PDF standard security handler. See section 3.5.2 of the PDF 1.6 reference. Args: password: owner_entry: p_entry: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. id1_entry: Returns: A Tuple (u-value, key) """ # 1. Create an encryption key based on the user password string, as # described in algorithm 3.2. rev: Literal[2] = 2 keylen = 5 key = _alg32(password, rev, keylen, owner_entry, p_entry, id1_entry) # 2. Encrypt the 32-byte padding string shown in step 1 of algorithm 3.2, # using an RC4 encryption function with the encryption key from the # preceding step. U = RC4_encrypt(key, _encryption_padding) # 3. Store the result of step 2 as the value of the /U entry in the # encryption dictionary. return U, key
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_security.py#L196-L231
39
[ 0, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35 ]
33.333333
[]
0
false
98.019802
36
1
100
16
def _alg34( password: str, owner_entry: ByteStringObject, p_entry: int, id1_entry: ByteStringObject, ) -> Tuple[bytes, bytes]: # 1. Create an encryption key based on the user password string, as # described in algorithm 3.2. rev: Literal[2] = 2 keylen = 5 key = _alg32(password, rev, keylen, owner_entry, p_entry, id1_entry) # 2. Encrypt the 32-byte padding string shown in step 1 of algorithm 3.2, # using an RC4 encryption function with the encryption key from the # preceding step. U = RC4_encrypt(key, _encryption_padding) # 3. Store the result of step 2 as the value of the /U entry in the # encryption dictionary. return U, key
24,185
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_security.py
_alg35
( password: str, rev: Literal[2, 3, 4], keylen: int, owner_entry: ByteStringObject, p_entry: int, id1_entry: ByteStringObject, metadata_encrypt: bool, )
return val + (b"\x00" * 16), key
Implementation of algorithm 3.4 of the PDF standard security handler. See section 3.5.2 of the PDF 1.6 reference. Args: password: rev: The encryption revision (see PDF standard) keylen: owner_entry: p_entry: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. id1_entry: metadata_encrypt: A boolean Returns: A tuple (value, key)
Implementation of algorithm 3.4 of the PDF standard security handler.
234
297
def _alg35( password: str, rev: Literal[2, 3, 4], keylen: int, owner_entry: ByteStringObject, p_entry: int, id1_entry: ByteStringObject, metadata_encrypt: bool, ) -> Tuple[bytes, bytes]: """ Implementation of algorithm 3.4 of the PDF standard security handler. See section 3.5.2 of the PDF 1.6 reference. Args: password: rev: The encryption revision (see PDF standard) keylen: owner_entry: p_entry: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. id1_entry: metadata_encrypt: A boolean Returns: A tuple (value, key) """ # 1. Create an encryption key based on the user password string, as # described in Algorithm 3.2. key = _alg32(password, rev, keylen, owner_entry, p_entry, id1_entry) # 2. Initialize the MD5 hash function and pass the 32-byte padding string # shown in step 1 of Algorithm 3.2 as input to this function. m = md5() m.update(_encryption_padding) # 3. Pass the first element of the file's file identifier array (the value # of the ID entry in the document's trailer dictionary; see Table 3.13 on # page 73) to the hash function and finish the hash. (See implementation # note 25 in Appendix H.) m.update(id1_entry.original_bytes) md5_hash = m.digest() # 4. Encrypt the 16-byte result of the hash, using an RC4 encryption # function with the encryption key from step 1. val = RC4_encrypt(key, md5_hash) # 5. Do the following 19 times: Take the output from the previous # invocation of the RC4 function and pass it as input to a new invocation # of the function; use an encryption key generated by taking each byte of # the original encryption key (obtained in step 2) and performing an XOR # operation between that byte and the single-byte value of the iteration # counter (from 1 to 19). for i in range(1, 20): new_key = b"" for k in key: new_key += b_(chr(ord_(k) ^ i)) val = RC4_encrypt(new_key, val) # 6. Append 16 bytes of arbitrary padding to the output from the final # invocation of the RC4 function and store the 32-byte result as the value # of the U entry in the encryption dictionary. # (implementer note: I don't know what "arbitrary padding" is supposed to # mean, so I have used null bytes. This seems to match a few other # people's implementations) return val + (b"\x00" * 16), key
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_security.py#L234-L297
39
[ 0, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63 ]
53.125
[]
0
false
98.019802
64
3
100
19
def _alg35( password: str, rev: Literal[2, 3, 4], keylen: int, owner_entry: ByteStringObject, p_entry: int, id1_entry: ByteStringObject, metadata_encrypt: bool, ) -> Tuple[bytes, bytes]: # 1. Create an encryption key based on the user password string, as # described in Algorithm 3.2. key = _alg32(password, rev, keylen, owner_entry, p_entry, id1_entry) # 2. Initialize the MD5 hash function and pass the 32-byte padding string # shown in step 1 of Algorithm 3.2 as input to this function. m = md5() m.update(_encryption_padding) # 3. Pass the first element of the file's file identifier array (the value # of the ID entry in the document's trailer dictionary; see Table 3.13 on # page 73) to the hash function and finish the hash. (See implementation # note 25 in Appendix H.) m.update(id1_entry.original_bytes) md5_hash = m.digest() # 4. Encrypt the 16-byte result of the hash, using an RC4 encryption # function with the encryption key from step 1. val = RC4_encrypt(key, md5_hash) # 5. Do the following 19 times: Take the output from the previous # invocation of the RC4 function and pass it as input to a new invocation # of the function; use an encryption key generated by taking each byte of # the original encryption key (obtained in step 2) and performing an XOR # operation between that byte and the single-byte value of the iteration # counter (from 1 to 19). for i in range(1, 20): new_key = b"" for k in key: new_key += b_(chr(ord_(k) ^ i)) val = RC4_encrypt(new_key, val) # 6. Append 16 bytes of arbitrary padding to the output from the final # invocation of the RC4 function and store the 32-byte result as the value # of the U entry in the encryption dictionary. # (implementer note: I don't know what "arbitrary padding" is supposed to # mean, so I have used null bytes. This seems to match a few other # people's implementations) return val + (b"\x00" * 16), key
24,186
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_security.py
RC4_encrypt
(key: Union[str, bytes], plaintext: bytes)
return b"".join(retval)
300
314
def RC4_encrypt(key: Union[str, bytes], plaintext: bytes) -> bytes: # TODO S = list(range(256)) j = 0 for i in range(256): j = (j + S[i] + ord_(key[i % len(key)])) % 256 S[i], S[j] = S[j], S[i] i, j = 0, 0 retval = [] for plaintext_char in plaintext: i = (i + 1) % 256 j = (j + S[i]) % 256 S[i], S[j] = S[j], S[i] t = S[(S[i] + S[j]) % 256] retval.append(b_(chr(ord_(plaintext_char) ^ t))) return b"".join(retval)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_security.py#L300-L314
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
98.019802
15
3
100
0
def RC4_encrypt(key: Union[str, bytes], plaintext: bytes) -> bytes: # TODO S = list(range(256)) j = 0 for i in range(256): j = (j + S[i] + ord_(key[i % len(key)])) % 256 S[i], S[j] = S[j], S[i] i, j = 0, 0 retval = [] for plaintext_char in plaintext: i = (i + 1) % 256 j = (j + S[i]) % 256 S[i], S[j] = S[j], S[i] t = S[(S[i] + S[j]) % 256] retval.append(b_(chr(ord_(plaintext_char) ^ t))) return b"".join(retval)
24,187
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
_padding
(data: bytes)
return (data + _PADDING)[:32]
233
234
def _padding(data: bytes) -> bytes: return (data + _PADDING)[:32]
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L233-L234
39
[ 0, 1 ]
100
[]
0
true
71.398747
2
1
100
0
def _padding(data: bytes) -> bytes: return (data + _PADDING)[:32]
24,188
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
CryptBase.encrypt
(self, data: bytes)
return data
48
49
def encrypt(self, data: bytes) -> bytes: # pragma: no cover return data
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L48-L49
39
[]
0
[]
0
false
71.398747
2
1
100
0
def encrypt(self, data: bytes) -> bytes: # pragma: no cover return data
24,189
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
CryptBase.decrypt
(self, data: bytes)
return data
51
52
def decrypt(self, data: bytes) -> bytes: # pragma: no cover return data
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L51-L52
39
[]
0
[]
0
false
71.398747
2
1
100
0
def decrypt(self, data: bytes) -> bytes: # pragma: no cover return data
24,190
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
CryptFilter.__init__
( self, stmCrypt: CryptBase, strCrypt: CryptBase, efCrypt: CryptBase )
169
174
def __init__( self, stmCrypt: CryptBase, strCrypt: CryptBase, efCrypt: CryptBase ) -> None: self.stmCrypt = stmCrypt self.strCrypt = strCrypt self.efCrypt = efCrypt
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L169-L174
39
[ 0, 3, 4, 5 ]
66.666667
[]
0
false
71.398747
6
1
100
0
def __init__( self, stmCrypt: CryptBase, strCrypt: CryptBase, efCrypt: CryptBase ) -> None: self.stmCrypt = stmCrypt self.strCrypt = strCrypt self.efCrypt = efCrypt
24,191
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
CryptFilter.encrypt_object
(self, obj: PdfObject)
return NotImplemented
176
178
def encrypt_object(self, obj: PdfObject) -> PdfObject: # TODO return NotImplemented
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L176-L178
39
[ 0, 1 ]
66.666667
[ 2 ]
33.333333
false
71.398747
3
1
66.666667
0
def encrypt_object(self, obj: PdfObject) -> PdfObject: # TODO return NotImplemented
24,192
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
CryptFilter.decrypt_object
(self, obj: PdfObject)
return obj
180
192
def decrypt_object(self, obj: PdfObject) -> PdfObject: if isinstance(obj, (ByteStringObject, TextStringObject)): data = self.strCrypt.decrypt(obj.original_bytes) obj = create_string_object(data) elif isinstance(obj, StreamObject): obj._data = self.stmCrypt.decrypt(obj._data) elif isinstance(obj, DictionaryObject): for dictkey, value in list(obj.items()): obj[dictkey] = self.decrypt_object(value) elif isinstance(obj, ArrayObject): for i in range(len(obj)): obj[i] = self.decrypt_object(obj[i]) return obj
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L180-L192
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
71.398747
13
7
100
0
def decrypt_object(self, obj: PdfObject) -> PdfObject: if isinstance(obj, (ByteStringObject, TextStringObject)): data = self.strCrypt.decrypt(obj.original_bytes) obj = create_string_object(data) elif isinstance(obj, StreamObject): obj._data = self.stmCrypt.decrypt(obj._data) elif isinstance(obj, DictionaryObject): for dictkey, value in list(obj.items()): obj[dictkey] = self.decrypt_object(value) elif isinstance(obj, ArrayObject): for i in range(len(obj)): obj[i] = self.decrypt_object(obj[i]) return obj
24,193
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
AlgV4.compute_key
( password: bytes, rev: int, key_size: int, o_entry: bytes, P: int, id1_entry: bytes, metadata_encrypted: bool, )
return u_hash_digest[:length]
Algorithm 2: Computing an encryption key. a) Pad or truncate the password string to exactly 32 bytes. If the password string is more than 32 bytes long, use only its first 32 bytes; if it is less than 32 bytes long, pad it by appending the required number of additional bytes from the beginning of the following padding string: < 28 BF 4E 5E 4E 75 8A 41 64 00 4E 56 FF FA 01 08 2E 2E 00 B6 D0 68 3E 80 2F 0C A9 FE 64 53 69 7A > That is, if the password string is n bytes long, append the first 32 - n bytes of the padding string to the end of the password string. If the password string is empty (zero-length), meaning there is no user password, substitute the entire padding string in its place. b) Initialize the MD5 hash function and pass the result of step (a) as input to this function. c) Pass the value of the encryption dictionary’s O entry to the MD5 hash function. ("Algorithm 3: Computing the encryption dictionary’s O (owner password) value" shows how the O value is computed.) d) Convert the integer value of the P entry to a 32-bit unsigned binary number and pass these bytes to the MD5 hash function, low-order byte first. e) Pass the first element of the file’s file identifier array (the value of the ID entry in the document’s trailer dictionary; see Table 15) to the MD5 hash function. f) (Security handlers of revision 4 or greater) If document metadata is not being encrypted, pass 4 bytes with the value 0xFFFFFFFF to the MD5 hash function. g) Finish the hash. h) (Security handlers of revision 3 or greater) Do the following 50 times: Take the output from the previous MD5 hash and pass the first n bytes of the output as input into a new MD5 hash, where n is the number of bytes of the encryption key as defined by the value of the encryption dictionary’s Length entry. i) Set the encryption key to the first n bytes of the output from the final MD5 hash, where n shall always be 5 for security handlers of revision 2 but, for security handlers of revision 3 or greater, shall depend on the value of the encryption dictionary’s Length entry. Args: password: The encryption secret as a bytes-string rev: The encryption revision (see PDF standard) key_size: The size of the key in bytes o_entry: The owner entry P: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. id1_entry: metadata_encrypted: A boolean indicating if the metadata is encrypted. Returns: The u_hash digest of length key_size
Algorithm 2: Computing an encryption key.
239
320
def compute_key( password: bytes, rev: int, key_size: int, o_entry: bytes, P: int, id1_entry: bytes, metadata_encrypted: bool, ) -> bytes: """ Algorithm 2: Computing an encryption key. a) Pad or truncate the password string to exactly 32 bytes. If the password string is more than 32 bytes long, use only its first 32 bytes; if it is less than 32 bytes long, pad it by appending the required number of additional bytes from the beginning of the following padding string: < 28 BF 4E 5E 4E 75 8A 41 64 00 4E 56 FF FA 01 08 2E 2E 00 B6 D0 68 3E 80 2F 0C A9 FE 64 53 69 7A > That is, if the password string is n bytes long, append the first 32 - n bytes of the padding string to the end of the password string. If the password string is empty (zero-length), meaning there is no user password, substitute the entire padding string in its place. b) Initialize the MD5 hash function and pass the result of step (a) as input to this function. c) Pass the value of the encryption dictionary’s O entry to the MD5 hash function. ("Algorithm 3: Computing the encryption dictionary’s O (owner password) value" shows how the O value is computed.) d) Convert the integer value of the P entry to a 32-bit unsigned binary number and pass these bytes to the MD5 hash function, low-order byte first. e) Pass the first element of the file’s file identifier array (the value of the ID entry in the document’s trailer dictionary; see Table 15) to the MD5 hash function. f) (Security handlers of revision 4 or greater) If document metadata is not being encrypted, pass 4 bytes with the value 0xFFFFFFFF to the MD5 hash function. g) Finish the hash. h) (Security handlers of revision 3 or greater) Do the following 50 times: Take the output from the previous MD5 hash and pass the first n bytes of the output as input into a new MD5 hash, where n is the number of bytes of the encryption key as defined by the value of the encryption dictionary’s Length entry. i) Set the encryption key to the first n bytes of the output from the final MD5 hash, where n shall always be 5 for security handlers of revision 2 but, for security handlers of revision 3 or greater, shall depend on the value of the encryption dictionary’s Length entry. Args: password: The encryption secret as a bytes-string rev: The encryption revision (see PDF standard) key_size: The size of the key in bytes o_entry: The owner entry P: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. id1_entry: metadata_encrypted: A boolean indicating if the metadata is encrypted. Returns: The u_hash digest of length key_size """ a = _padding(password) u_hash = hashlib.md5(a) u_hash.update(o_entry) u_hash.update(struct.pack("<I", P)) u_hash.update(id1_entry) if rev >= 4 and metadata_encrypted is False: u_hash.update(b"\xff\xff\xff\xff") u_hash_digest = u_hash.digest() length = key_size // 8 if rev >= 3: for _ in range(50): u_hash_digest = hashlib.md5(u_hash_digest[:length]).digest() return u_hash_digest[:length]
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L239-L320
39
[ 0, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81 ]
18.292683
[]
0
false
71.398747
82
5
100
58
def compute_key( password: bytes, rev: int, key_size: int, o_entry: bytes, P: int, id1_entry: bytes, metadata_encrypted: bool, ) -> bytes: a = _padding(password) u_hash = hashlib.md5(a) u_hash.update(o_entry) u_hash.update(struct.pack("<I", P)) u_hash.update(id1_entry) if rev >= 4 and metadata_encrypted is False: u_hash.update(b"\xff\xff\xff\xff") u_hash_digest = u_hash.digest() length = key_size // 8 if rev >= 3: for _ in range(50): u_hash_digest = hashlib.md5(u_hash_digest[:length]).digest() return u_hash_digest[:length]
24,194
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
AlgV4.compute_O_value_key
(owner_password: bytes, rev: int, key_size: int)
return rc4_key
Algorithm 3: Computing the encryption dictionary’s O (owner password) value. a) Pad or truncate the owner password string as described in step (a) of "Algorithm 2: Computing an encryption key". If there is no owner password, use the user password instead. b) Initialize the MD5 hash function and pass the result of step (a) as input to this function. c) (Security handlers of revision 3 or greater) Do the following 50 times: Take the output from the previous MD5 hash and pass it as input into a new MD5 hash. d) Create an RC4 encryption key using the first n bytes of the output from the final MD5 hash, where n shall always be 5 for security handlers of revision 2 but, for security handlers of revision 3 or greater, shall depend on the value of the encryption dictionary’s Length entry. e) Pad or truncate the user password string as described in step (a) of "Algorithm 2: Computing an encryption key". f) Encrypt the result of step (e), using an RC4 encryption function with the encryption key obtained in step (d). g) (Security handlers of revision 3 or greater) Do the following 19 times: Take the output from the previous invocation of the RC4 function and pass it as input to a new invocation of the function; use an encryption key generated by taking each byte of the encryption key obtained in step (d) and performing an XOR (exclusive or) operation between that byte and the single-byte value of the iteration counter (from 1 to 19). h) Store the output from the final invocation of the RC4 function as the value of the O entry in the encryption dictionary. Args: owner_password: rev: The encryption revision (see PDF standard) key_size: The size of the key in bytes Returns: The RC4 key
Algorithm 3: Computing the encryption dictionary’s O (owner password) value.
323
371
def compute_O_value_key(owner_password: bytes, rev: int, key_size: int) -> bytes: """ Algorithm 3: Computing the encryption dictionary’s O (owner password) value. a) Pad or truncate the owner password string as described in step (a) of "Algorithm 2: Computing an encryption key". If there is no owner password, use the user password instead. b) Initialize the MD5 hash function and pass the result of step (a) as input to this function. c) (Security handlers of revision 3 or greater) Do the following 50 times: Take the output from the previous MD5 hash and pass it as input into a new MD5 hash. d) Create an RC4 encryption key using the first n bytes of the output from the final MD5 hash, where n shall always be 5 for security handlers of revision 2 but, for security handlers of revision 3 or greater, shall depend on the value of the encryption dictionary’s Length entry. e) Pad or truncate the user password string as described in step (a) of "Algorithm 2: Computing an encryption key". f) Encrypt the result of step (e), using an RC4 encryption function with the encryption key obtained in step (d). g) (Security handlers of revision 3 or greater) Do the following 19 times: Take the output from the previous invocation of the RC4 function and pass it as input to a new invocation of the function; use an encryption key generated by taking each byte of the encryption key obtained in step (d) and performing an XOR (exclusive or) operation between that byte and the single-byte value of the iteration counter (from 1 to 19). h) Store the output from the final invocation of the RC4 function as the value of the O entry in the encryption dictionary. Args: owner_password: rev: The encryption revision (see PDF standard) key_size: The size of the key in bytes Returns: The RC4 key """ a = _padding(owner_password) o_hash_digest = hashlib.md5(a).digest() if rev >= 3: for _ in range(50): o_hash_digest = hashlib.md5(o_hash_digest).digest() rc4_key = o_hash_digest[: key_size // 8] return rc4_key
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L323-L371
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48 ]
100
[]
0
true
71.398747
49
3
100
37
def compute_O_value_key(owner_password: bytes, rev: int, key_size: int) -> bytes: a = _padding(owner_password) o_hash_digest = hashlib.md5(a).digest() if rev >= 3: for _ in range(50): o_hash_digest = hashlib.md5(o_hash_digest).digest() rc4_key = o_hash_digest[: key_size // 8] return rc4_key
24,195
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
AlgV4.compute_O_value
(rc4_key: bytes, user_password: bytes, rev: int)
return rc4_enc
See :func:`compute_O_value_key`. Args: rc4_key: user_password: rev: The encryption revision (see PDF standard) Returns: The RC4 encrypted
See :func:`compute_O_value_key`.
374
392
def compute_O_value(rc4_key: bytes, user_password: bytes, rev: int) -> bytes: """ See :func:`compute_O_value_key`. Args: rc4_key: user_password: rev: The encryption revision (see PDF standard) Returns: The RC4 encrypted """ a = _padding(user_password) rc4_enc = RC4_encrypt(rc4_key, a) if rev >= 3: for i in range(1, 20): key = bytes(bytearray(x ^ i for x in rc4_key)) rc4_enc = RC4_encrypt(key, rc4_enc) return rc4_enc
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L374-L392
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
63.157895
[ 12, 13, 14, 15, 16, 17, 18 ]
36.842105
false
71.398747
19
3
63.157895
9
def compute_O_value(rc4_key: bytes, user_password: bytes, rev: int) -> bytes: a = _padding(user_password) rc4_enc = RC4_encrypt(rc4_key, a) if rev >= 3: for i in range(1, 20): key = bytes(bytearray(x ^ i for x in rc4_key)) rc4_enc = RC4_encrypt(key, rc4_enc) return rc4_enc
24,196
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
AlgV4.compute_U_value
(key: bytes, rev: int, id1_entry: bytes)
return _padding(rc4_enc)
Algorithm 4: Computing the encryption dictionary’s U (user password) value. (Security handlers of revision 2) a) Create an encryption key based on the user password string, as described in "Algorithm 2: Computing an encryption key". b) Encrypt the 32-byte padding string shown in step (a) of "Algorithm 2: Computing an encryption key", using an RC4 encryption function with the encryption key from the preceding step. c) Store the result of step (b) as the value of the U entry in the encryption dictionary. Args: key: rev: The encryption revision (see PDF standard) id1_entry: Returns: The value
Algorithm 4: Computing the encryption dictionary’s U (user password) value.
395
452
def compute_U_value(key: bytes, rev: int, id1_entry: bytes) -> bytes: """ Algorithm 4: Computing the encryption dictionary’s U (user password) value. (Security handlers of revision 2) a) Create an encryption key based on the user password string, as described in "Algorithm 2: Computing an encryption key". b) Encrypt the 32-byte padding string shown in step (a) of "Algorithm 2: Computing an encryption key", using an RC4 encryption function with the encryption key from the preceding step. c) Store the result of step (b) as the value of the U entry in the encryption dictionary. Args: key: rev: The encryption revision (see PDF standard) id1_entry: Returns: The value """ if rev <= 2: value = RC4_encrypt(key, _PADDING) return value """ Algorithm 5: Computing the encryption dictionary’s U (user password) value. (Security handlers of revision 3 or greater) a) Create an encryption key based on the user password string, as described in "Algorithm 2: Computing an encryption key". b) Initialize the MD5 hash function and pass the 32-byte padding string shown in step (a) of "Algorithm 2: Computing an encryption key" as input to this function. c) Pass the first element of the file’s file identifier array (the value of the ID entry in the document’s trailer dictionary; see Table 15) to the hash function and finish the hash. d) Encrypt the 16-byte result of the hash, using an RC4 encryption function with the encryption key from step (a). e) Do the following 19 times: Take the output from the previous invocation of the RC4 function and pass it as input to a new invocation of the function; use an encryption key generated by taking each byte of the original encryption key obtained in step (a) and performing an XOR (exclusive or) operation between that byte and the single-byte value of the iteration counter (from 1 to 19). f) Append 16 bytes of arbitrary padding to the output from the final invocation of the RC4 function and store the 32-byte result as the value of the U entry in the encryption dictionary. """ u_hash = hashlib.md5(_PADDING) u_hash.update(id1_entry) rc4_enc = RC4_encrypt(key, u_hash.digest()) for i in range(1, 20): rc4_key = bytes(bytearray(x ^ i for x in key)) rc4_enc = RC4_encrypt(rc4_key, rc4_enc) return _padding(rc4_enc)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L395-L452
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 ]
100
[]
0
true
71.398747
58
3
100
19
def compute_U_value(key: bytes, rev: int, id1_entry: bytes) -> bytes: if rev <= 2: value = RC4_encrypt(key, _PADDING) return value u_hash = hashlib.md5(_PADDING) u_hash.update(id1_entry) rc4_enc = RC4_encrypt(key, u_hash.digest()) for i in range(1, 20): rc4_key = bytes(bytearray(x ^ i for x in key)) rc4_enc = RC4_encrypt(rc4_key, rc4_enc) return _padding(rc4_enc)
24,197
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
AlgV4.verify_user_password
( user_password: bytes, rev: int, key_size: int, o_entry: bytes, u_entry: bytes, P: int, id1_entry: bytes, metadata_encrypted: bool, )
return key
Algorithm 6: Authenticating the user password. a) Perform all but the last step of "Algorithm 4: Computing the encryption dictionary’s U (user password) value (Security handlers of revision 2)" or "Algorithm 5: Computing the encryption dictionary’s U (user password) value (Security handlers of revision 3 or greater)" using the supplied password string. b) If the result of step (a) is equal to the value of the encryption dictionary’s U entry (comparing on the first 16 bytes in the case of security handlers of revision 3 or greater), the password supplied is the correct user password. The key obtained in step (a) (that is, in the first step of "Algorithm 4: Computing the encryption dictionary’s U (user password) value (Security handlers of revision 2)" or "Algorithm 5: Computing the encryption dictionary’s U (user password) value (Security handlers of revision 3 or greater)") shall be used to decrypt the document. Args: user_password: The user passwort as a bytes stream rev: The encryption revision (see PDF standard) key_size: The size of the key in bytes o_entry: The owner entry u_entry: The user entry P: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. id1_entry: metadata_encrypted: A boolean indicating if the metadata is encrypted. Returns: The key
Algorithm 6: Authenticating the user password.
455
504
def verify_user_password( user_password: bytes, rev: int, key_size: int, o_entry: bytes, u_entry: bytes, P: int, id1_entry: bytes, metadata_encrypted: bool, ) -> bytes: """ Algorithm 6: Authenticating the user password. a) Perform all but the last step of "Algorithm 4: Computing the encryption dictionary’s U (user password) value (Security handlers of revision 2)" or "Algorithm 5: Computing the encryption dictionary’s U (user password) value (Security handlers of revision 3 or greater)" using the supplied password string. b) If the result of step (a) is equal to the value of the encryption dictionary’s U entry (comparing on the first 16 bytes in the case of security handlers of revision 3 or greater), the password supplied is the correct user password. The key obtained in step (a) (that is, in the first step of "Algorithm 4: Computing the encryption dictionary’s U (user password) value (Security handlers of revision 2)" or "Algorithm 5: Computing the encryption dictionary’s U (user password) value (Security handlers of revision 3 or greater)") shall be used to decrypt the document. Args: user_password: The user passwort as a bytes stream rev: The encryption revision (see PDF standard) key_size: The size of the key in bytes o_entry: The owner entry u_entry: The user entry P: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. id1_entry: metadata_encrypted: A boolean indicating if the metadata is encrypted. Returns: The key """ key = AlgV4.compute_key( user_password, rev, key_size, o_entry, P, id1_entry, metadata_encrypted ) u_value = AlgV4.compute_U_value(key, rev, id1_entry) if rev >= 3: u_value = u_value[:16] u_entry = u_entry[:16] if u_value != u_entry: key = b"" return key
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L455-L504
39
[ 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49 ]
24
[]
0
false
71.398747
50
3
100
28
def verify_user_password( user_password: bytes, rev: int, key_size: int, o_entry: bytes, u_entry: bytes, P: int, id1_entry: bytes, metadata_encrypted: bool, ) -> bytes: key = AlgV4.compute_key( user_password, rev, key_size, o_entry, P, id1_entry, metadata_encrypted ) u_value = AlgV4.compute_U_value(key, rev, id1_entry) if rev >= 3: u_value = u_value[:16] u_entry = u_entry[:16] if u_value != u_entry: key = b"" return key
24,198
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
AlgV4.verify_owner_password
( owner_password: bytes, rev: int, key_size: int, o_entry: bytes, u_entry: bytes, P: int, id1_entry: bytes, metadata_encrypted: bool, )
return AlgV4.verify_user_password( user_password, rev, key_size, o_entry, u_entry, P, id1_entry, metadata_encrypted, )
Algorithm 7: Authenticating the owner password. a) Compute an encryption key from the supplied password string, as described in steps (a) to (d) of "Algorithm 3: Computing the encryption dictionary’s O (owner password) value". b) (Security handlers of revision 2 only) Decrypt the value of the encryption dictionary’s O entry, using an RC4 encryption function with the encryption key computed in step (a). (Security handlers of revision 3 or greater) Do the following 20 times: Decrypt the value of the encryption dictionary’s O entry (first iteration) or the output from the previous iteration (all subsequent iterations), using an RC4 encryption function with a different encryption key at each iteration. The key shall be generated by taking the original key (obtained in step (a)) and performing an XOR (exclusive or) operation between each byte of the key and the single-byte value of the iteration counter (from 19 to 0). c) The result of step (b) purports to be the user password. Authenticate this user password using "Algorithm 6: Authenticating the user password". If it is correct, the password supplied is the correct owner password. Args: owner_password: rev: The encryption revision (see PDF standard) key_size: The size of the key in bytes o_entry: The owner entry u_entry: The user entry P: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. id1_entry: metadata_encrypted: A boolean indicating if the metadata is encrypted. Returns: bytes
Algorithm 7: Authenticating the owner password.
507
567
def verify_owner_password( owner_password: bytes, rev: int, key_size: int, o_entry: bytes, u_entry: bytes, P: int, id1_entry: bytes, metadata_encrypted: bool, ) -> bytes: """ Algorithm 7: Authenticating the owner password. a) Compute an encryption key from the supplied password string, as described in steps (a) to (d) of "Algorithm 3: Computing the encryption dictionary’s O (owner password) value". b) (Security handlers of revision 2 only) Decrypt the value of the encryption dictionary’s O entry, using an RC4 encryption function with the encryption key computed in step (a). (Security handlers of revision 3 or greater) Do the following 20 times: Decrypt the value of the encryption dictionary’s O entry (first iteration) or the output from the previous iteration (all subsequent iterations), using an RC4 encryption function with a different encryption key at each iteration. The key shall be generated by taking the original key (obtained in step (a)) and performing an XOR (exclusive or) operation between each byte of the key and the single-byte value of the iteration counter (from 19 to 0). c) The result of step (b) purports to be the user password. Authenticate this user password using "Algorithm 6: Authenticating the user password". If it is correct, the password supplied is the correct owner password. Args: owner_password: rev: The encryption revision (see PDF standard) key_size: The size of the key in bytes o_entry: The owner entry u_entry: The user entry P: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. id1_entry: metadata_encrypted: A boolean indicating if the metadata is encrypted. Returns: bytes """ rc4_key = AlgV4.compute_O_value_key(owner_password, rev, key_size) if rev <= 2: user_password = RC4_decrypt(rc4_key, o_entry) else: user_password = o_entry for i in range(19, -1, -1): key = bytes(bytearray(x ^ i for x in rc4_key)) user_password = RC4_decrypt(key, user_password) return AlgV4.verify_user_password( user_password, rev, key_size, o_entry, u_entry, P, id1_entry, metadata_encrypted, )
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L507-L567
39
[ 0, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 ]
34.42623
[]
0
false
71.398747
61
3
100
30
def verify_owner_password( owner_password: bytes, rev: int, key_size: int, o_entry: bytes, u_entry: bytes, P: int, id1_entry: bytes, metadata_encrypted: bool, ) -> bytes: rc4_key = AlgV4.compute_O_value_key(owner_password, rev, key_size) if rev <= 2: user_password = RC4_decrypt(rc4_key, o_entry) else: user_password = o_entry for i in range(19, -1, -1): key = bytes(bytearray(x ^ i for x in rc4_key)) user_password = RC4_decrypt(key, user_password) return AlgV4.verify_user_password( user_password, rev, key_size, o_entry, u_entry, P, id1_entry, metadata_encrypted, )
24,199
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
AlgV5.verify_owner_password
( R: int, password: bytes, o_value: bytes, oe_value: bytes, u_value: bytes )
return key
Algorithm 3.2a Computing an encryption key. To understand the algorithm below, it is necessary to treat the O and U strings in the Encrypt dictionary as made up of three sections. The first 32 bytes are a hash value (explained below). The next 8 bytes are called the Validation Salt. The final 8 bytes are called the Key Salt. 1. The password string is generated from Unicode input by processing the input string with the SASLprep (IETF RFC 4013) profile of stringprep (IETF RFC 3454), and then converting to a UTF-8 representation. 2. Truncate the UTF-8 representation to 127 bytes if it is longer than 127 bytes. 3. Test the password against the owner key by computing the SHA-256 hash of the UTF-8 password concatenated with the 8 bytes of owner Validation Salt, concatenated with the 48-byte U string. If the 32-byte result matches the first 32 bytes of the O string, this is the owner password. Compute an intermediate owner key by computing the SHA-256 hash of the UTF-8 password concatenated with the 8 bytes of owner Key Salt, concatenated with the 48-byte U string. The 32-byte result is the key used to decrypt the 32-byte OE string using AES-256 in CBC mode with no padding and an initialization vector of zero. The 32-byte result is the file encryption key. 4. Test the password against the user key by computing the SHA-256 hash of the UTF-8 password concatenated with the 8 bytes of user Validation Salt. If the 32 byte result matches the first 32 bytes of the U string, this is the user password. Compute an intermediate user key by computing the SHA-256 hash of the UTF-8 password concatenated with the 8 bytes of user Key Salt. The 32-byte result is the key used to decrypt the 32-byte UE string using AES-256 in CBC mode with no padding and an initialization vector of zero. The 32-byte result is the file encryption key. 5. Decrypt the 16-byte Perms string using AES-256 in ECB mode with an initialization vector of zero and the file encryption key as the key. Verify that bytes 9-11 of the result are the characters ‘a’, ‘d’, ‘b’. Bytes 0-3 of the decrypted Perms entry, treated as a little-endian integer, are the user permissions. They should match the value in the P key. Args: R: A number specifying which revision of the standard security handler shall be used to interpret this dictionary password: The owner password o_value: A 32-byte string, based on both the owner and user passwords, that shall be used in computing the encryption key and in determining whether a valid owner password was entered oe_value: u_value: A 32-byte string, based on the user password, that shall be used in determining whether to prompt the user for a password and, if so, whether a valid user or owner password was entered. Returns: The key
Algorithm 3.2a Computing an encryption key.
572
628
def verify_owner_password( R: int, password: bytes, o_value: bytes, oe_value: bytes, u_value: bytes ) -> bytes: """ Algorithm 3.2a Computing an encryption key. To understand the algorithm below, it is necessary to treat the O and U strings in the Encrypt dictionary as made up of three sections. The first 32 bytes are a hash value (explained below). The next 8 bytes are called the Validation Salt. The final 8 bytes are called the Key Salt. 1. The password string is generated from Unicode input by processing the input string with the SASLprep (IETF RFC 4013) profile of stringprep (IETF RFC 3454), and then converting to a UTF-8 representation. 2. Truncate the UTF-8 representation to 127 bytes if it is longer than 127 bytes. 3. Test the password against the owner key by computing the SHA-256 hash of the UTF-8 password concatenated with the 8 bytes of owner Validation Salt, concatenated with the 48-byte U string. If the 32-byte result matches the first 32 bytes of the O string, this is the owner password. Compute an intermediate owner key by computing the SHA-256 hash of the UTF-8 password concatenated with the 8 bytes of owner Key Salt, concatenated with the 48-byte U string. The 32-byte result is the key used to decrypt the 32-byte OE string using AES-256 in CBC mode with no padding and an initialization vector of zero. The 32-byte result is the file encryption key. 4. Test the password against the user key by computing the SHA-256 hash of the UTF-8 password concatenated with the 8 bytes of user Validation Salt. If the 32 byte result matches the first 32 bytes of the U string, this is the user password. Compute an intermediate user key by computing the SHA-256 hash of the UTF-8 password concatenated with the 8 bytes of user Key Salt. The 32-byte result is the key used to decrypt the 32-byte UE string using AES-256 in CBC mode with no padding and an initialization vector of zero. The 32-byte result is the file encryption key. 5. Decrypt the 16-byte Perms string using AES-256 in ECB mode with an initialization vector of zero and the file encryption key as the key. Verify that bytes 9-11 of the result are the characters ‘a’, ‘d’, ‘b’. Bytes 0-3 of the decrypted Perms entry, treated as a little-endian integer, are the user permissions. They should match the value in the P key. Args: R: A number specifying which revision of the standard security handler shall be used to interpret this dictionary password: The owner password o_value: A 32-byte string, based on both the owner and user passwords, that shall be used in computing the encryption key and in determining whether a valid owner password was entered oe_value: u_value: A 32-byte string, based on the user password, that shall be used in determining whether to prompt the user for a password and, if so, whether a valid user or owner password was entered. Returns: The key """ password = password[:127] if ( AlgV5.calculate_hash(R, password, o_value[32:40], u_value[:48]) != o_value[:32] ): return b"" iv = bytes(0 for _ in range(16)) tmp_key = AlgV5.calculate_hash(R, password, o_value[40:48], u_value[:48]) key = AES_CBC_decrypt(tmp_key, iv, oe_value) return key
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L572-L628
39
[ 0, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55 ]
19.298246
[ 56 ]
1.754386
false
71.398747
57
2
98.245614
42
def verify_owner_password( R: int, password: bytes, o_value: bytes, oe_value: bytes, u_value: bytes ) -> bytes: password = password[:127] if ( AlgV5.calculate_hash(R, password, o_value[32:40], u_value[:48]) != o_value[:32] ): return b"" iv = bytes(0 for _ in range(16)) tmp_key = AlgV5.calculate_hash(R, password, o_value[40:48], u_value[:48]) key = AES_CBC_decrypt(tmp_key, iv, oe_value) return key
24,200
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
AlgV5.verify_user_password
( R: int, password: bytes, u_value: bytes, ue_value: bytes )
return AES_CBC_decrypt(tmp_key, iv, ue_value)
See :func:`verify_owner_password`. Args: R: A number specifying which revision of the standard security handler shall be used to interpret this dictionary password: The user password u_value: A 32-byte string, based on the user password, that shall be used in determining whether to prompt the user for a password and, if so, whether a valid user or owner password was entered. ue_value: Returns: bytes
See :func:`verify_owner_password`.
631
654
def verify_user_password( R: int, password: bytes, u_value: bytes, ue_value: bytes ) -> bytes: """ See :func:`verify_owner_password`. Args: R: A number specifying which revision of the standard security handler shall be used to interpret this dictionary password: The user password u_value: A 32-byte string, based on the user password, that shall be used in determining whether to prompt the user for a password and, if so, whether a valid user or owner password was entered. ue_value: Returns: bytes """ password = password[:127] if AlgV5.calculate_hash(R, password, u_value[32:40], b"") != u_value[:32]: return b"" iv = bytes(0 for _ in range(16)) tmp_key = AlgV5.calculate_hash(R, password, u_value[40:48], b"") return AES_CBC_decrypt(tmp_key, iv, ue_value)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L631-L654
39
[ 0, 17, 18, 19, 21, 22, 23 ]
29.166667
[ 20 ]
4.166667
false
71.398747
24
2
95.833333
13
def verify_user_password( R: int, password: bytes, u_value: bytes, ue_value: bytes ) -> bytes: password = password[:127] if AlgV5.calculate_hash(R, password, u_value[32:40], b"") != u_value[:32]: return b"" iv = bytes(0 for _ in range(16)) tmp_key = AlgV5.calculate_hash(R, password, u_value[40:48], b"") return AES_CBC_decrypt(tmp_key, iv, ue_value)
24,201
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
AlgV5.calculate_hash
(R: int, password: bytes, salt: bytes, udata: bytes)
return K[:32]
657
675
def calculate_hash(R: int, password: bytes, salt: bytes, udata: bytes) -> bytes: # from https://github.com/qpdf/qpdf/blob/main/libqpdf/QPDF_encryption.cc K = hashlib.sha256(password + salt + udata).digest() if R < 6: return K count = 0 while True: count += 1 K1 = password + K + udata E = AES_CBC_encrypt(K[:16], K[16:32], K1 * 64) hash_fn = ( hashlib.sha256, hashlib.sha384, hashlib.sha512, )[sum(E[:16]) % 3] K = hash_fn(E).digest() if count >= 64 and E[-1] <= count - 32: break return K[:32]
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L657-L675
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
52.631579
[ 10, 15, 16, 17, 18 ]
26.315789
false
71.398747
19
5
73.684211
0
def calculate_hash(R: int, password: bytes, salt: bytes, udata: bytes) -> bytes: # from https://github.com/qpdf/qpdf/blob/main/libqpdf/QPDF_encryption.cc K = hashlib.sha256(password + salt + udata).digest() if R < 6: return K count = 0 while True: count += 1 K1 = password + K + udata E = AES_CBC_encrypt(K[:16], K[16:32], K1 * 64) hash_fn = ( hashlib.sha256, hashlib.sha384, hashlib.sha512, )[sum(E[:16]) % 3] K = hash_fn(E).digest() if count >= 64 and E[-1] <= count - 32: break return K[:32]
24,202
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
AlgV5.verify_perms
( key: bytes, perms: bytes, p: int, metadata_encrypted: bool )
return p1 == p2[:12]
See :func:`verify_owner_password` and :func:`compute_perms_value`. Args: key: The owner password perms: p: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. metadata_encrypted: Returns: A boolean
See :func:`verify_owner_password` and :func:`compute_perms_value`.
678
700
def verify_perms( key: bytes, perms: bytes, p: int, metadata_encrypted: bool ) -> bool: """ See :func:`verify_owner_password` and :func:`compute_perms_value`. Args: key: The owner password perms: p: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. metadata_encrypted: Returns: A boolean """ b8 = b"T" if metadata_encrypted else b"F" p1 = struct.pack("<I", p) + b"\xff\xff\xff\xff" + b8 + b"adb" p2 = AES_ECB_decrypt(key, perms) return p1 == p2[:12]
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L678-L700
39
[ 0 ]
4.347826
[ 19, 20, 21, 22 ]
17.391304
false
71.398747
23
1
82.608696
14
def verify_perms( key: bytes, perms: bytes, p: int, metadata_encrypted: bool ) -> bool: b8 = b"T" if metadata_encrypted else b"F" p1 = struct.pack("<I", p) + b"\xff\xff\xff\xff" + b8 + b"adb" p2 = AES_ECB_decrypt(key, perms) return p1 == p2[:12]
24,203
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
AlgV5.generate_values
( user_password: bytes, owner_password: bytes, key: bytes, p: int, metadata_encrypted: bool, )
return { "/U": u_value, "/UE": ue_value, "/O": o_value, "/OE": oe_value, "/Perms": perms, }
703
719
def generate_values( user_password: bytes, owner_password: bytes, key: bytes, p: int, metadata_encrypted: bool, ) -> Dict[Any, Any]: u_value, ue_value = AlgV5.compute_U_value(user_password, key) o_value, oe_value = AlgV5.compute_O_value(owner_password, key, u_value) perms = AlgV5.compute_Perms_value(key, p, metadata_encrypted) return { "/U": u_value, "/UE": ue_value, "/O": o_value, "/OE": oe_value, "/Perms": perms, }
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L703-L719
39
[ 0 ]
5.882353
[ 7, 8, 9, 10 ]
23.529412
false
71.398747
17
1
76.470588
0
def generate_values( user_password: bytes, owner_password: bytes, key: bytes, p: int, metadata_encrypted: bool, ) -> Dict[Any, Any]: u_value, ue_value = AlgV5.compute_U_value(user_password, key) o_value, oe_value = AlgV5.compute_O_value(owner_password, key, u_value) perms = AlgV5.compute_Perms_value(key, p, metadata_encrypted) return { "/U": u_value, "/UE": ue_value, "/O": o_value, "/OE": oe_value, "/Perms": perms, }
24,204
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
AlgV5.compute_U_value
(password: bytes, key: bytes)
return u_value, ue_value
Algorithm 3.8 Computing the encryption dictionary’s U (user password) and UE (user encryption key) values 1. Generate 16 random bytes of data using a strong random number generator. The first 8 bytes are the User Validation Salt. The second 8 bytes are the User Key Salt. Compute the 32-byte SHA-256 hash of the password concatenated with the User Validation Salt. The 48-byte string consisting of the 32-byte hash followed by the User Validation Salt followed by the User Key Salt is stored as the U key. 2. Compute the 32-byte SHA-256 hash of the password concatenated with the User Key Salt. Using this hash as the key, encrypt the file encryption key using AES-256 in CBC mode with no padding and an initialization vector of zero. The resulting 32-byte string is stored as the UE key. Args: password: key: Returns: A tuple (u-value, ue value)
Algorithm 3.8 Computing the encryption dictionary’s U (user password) and UE (user encryption key) values
722
749
def compute_U_value(password: bytes, key: bytes) -> Tuple[bytes, bytes]: """ Algorithm 3.8 Computing the encryption dictionary’s U (user password) and UE (user encryption key) values 1. Generate 16 random bytes of data using a strong random number generator. The first 8 bytes are the User Validation Salt. The second 8 bytes are the User Key Salt. Compute the 32-byte SHA-256 hash of the password concatenated with the User Validation Salt. The 48-byte string consisting of the 32-byte hash followed by the User Validation Salt followed by the User Key Salt is stored as the U key. 2. Compute the 32-byte SHA-256 hash of the password concatenated with the User Key Salt. Using this hash as the key, encrypt the file encryption key using AES-256 in CBC mode with no padding and an initialization vector of zero. The resulting 32-byte string is stored as the UE key. Args: password: key: Returns: A tuple (u-value, ue value) """ random_bytes = bytes(random.randrange(0, 256) for _ in range(16)) val_salt = random_bytes[:8] key_salt = random_bytes[8:] u_value = hashlib.sha256(password + val_salt).digest() + val_salt + key_salt tmp_key = hashlib.sha256(password + key_salt).digest() iv = bytes(0 for _ in range(16)) ue_value = AES_CBC_encrypt(tmp_key, iv, key) return u_value, ue_value
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L722-L749
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
67.857143
[ 19, 20, 21, 22, 24, 25, 26, 27 ]
28.571429
false
71.398747
28
1
71.428571
16
def compute_U_value(password: bytes, key: bytes) -> Tuple[bytes, bytes]: random_bytes = bytes(random.randrange(0, 256) for _ in range(16)) val_salt = random_bytes[:8] key_salt = random_bytes[8:] u_value = hashlib.sha256(password + val_salt).digest() + val_salt + key_salt tmp_key = hashlib.sha256(password + key_salt).digest() iv = bytes(0 for _ in range(16)) ue_value = AES_CBC_encrypt(tmp_key, iv, key) return u_value, ue_value
24,205
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
AlgV5.compute_O_value
( password: bytes, key: bytes, u_value: bytes )
return o_value, oe_value
Algorithm 3.9 Computing the encryption dictionary’s O (owner password) and OE (owner encryption key) values. 1. Generate 16 random bytes of data using a strong random number generator. The first 8 bytes are the Owner Validation Salt. The second 8 bytes are the Owner Key Salt. Compute the 32-byte SHA-256 hash of the password concatenated with the Owner Validation Salt and then concatenated with the 48-byte U string as generated in Algorithm 3.8. The 48-byte string consisting of the 32-byte hash followed by the Owner Validation Salt followed by the Owner Key Salt is stored as the O key. 2. Compute the 32-byte SHA-256 hash of the password concatenated with the Owner Key Salt and then concatenated with the 48-byte U string as generated in Algorithm 3.8. Using this hash as the key, encrypt the file encryption key using AES-256 in CBC mode with no padding and an initialization vector of zero. The resulting 32-byte string is stored as the OE key. Args: password: key: u_value: A 32-byte string, based on the user password, that shall be used in determining whether to prompt the user for a password and, if so, whether a valid user or owner password was entered. Returns: A tuple (O value, OE value)
Algorithm 3.9 Computing the encryption dictionary’s O (owner password) and OE (owner encryption key) values.
752
788
def compute_O_value( password: bytes, key: bytes, u_value: bytes ) -> Tuple[bytes, bytes]: """ Algorithm 3.9 Computing the encryption dictionary’s O (owner password) and OE (owner encryption key) values. 1. Generate 16 random bytes of data using a strong random number generator. The first 8 bytes are the Owner Validation Salt. The second 8 bytes are the Owner Key Salt. Compute the 32-byte SHA-256 hash of the password concatenated with the Owner Validation Salt and then concatenated with the 48-byte U string as generated in Algorithm 3.8. The 48-byte string consisting of the 32-byte hash followed by the Owner Validation Salt followed by the Owner Key Salt is stored as the O key. 2. Compute the 32-byte SHA-256 hash of the password concatenated with the Owner Key Salt and then concatenated with the 48-byte U string as generated in Algorithm 3.8. Using this hash as the key, encrypt the file encryption key using AES-256 in CBC mode with no padding and an initialization vector of zero. The resulting 32-byte string is stored as the OE key. Args: password: key: u_value: A 32-byte string, based on the user password, that shall be used in determining whether to prompt the user for a password and, if so, whether a valid user or owner password was entered. Returns: A tuple (O value, OE value) """ random_bytes = bytes(random.randrange(0, 256) for _ in range(16)) val_salt = random_bytes[:8] key_salt = random_bytes[8:] o_value = ( hashlib.sha256(password + val_salt + u_value).digest() + val_salt + key_salt ) tmp_key = hashlib.sha256(password + key_salt + u_value).digest() iv = bytes(0 for _ in range(16)) oe_value = AES_CBC_encrypt(tmp_key, iv, key) return o_value, oe_value
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L752-L788
39
[ 0 ]
2.702703
[ 26, 27, 28, 29, 33, 34, 35, 36 ]
21.621622
false
71.398747
37
1
78.378378
21
def compute_O_value( password: bytes, key: bytes, u_value: bytes ) -> Tuple[bytes, bytes]: random_bytes = bytes(random.randrange(0, 256) for _ in range(16)) val_salt = random_bytes[:8] key_salt = random_bytes[8:] o_value = ( hashlib.sha256(password + val_salt + u_value).digest() + val_salt + key_salt ) tmp_key = hashlib.sha256(password + key_salt + u_value).digest() iv = bytes(0 for _ in range(16)) oe_value = AES_CBC_encrypt(tmp_key, iv, key) return o_value, oe_value
24,206
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
AlgV5.compute_Perms_value
(key: bytes, p: int, metadata_encrypted: bool)
return perms
Algorithm 3.10 Computing the encryption dictionary’s Perms (permissions) value 1. Extend the permissions (contents of the P integer) to 64 bits by setting the upper 32 bits to all 1’s. (This allows for future extension without changing the format.) 2. Record the 8 bytes of permission in the bytes 0-7 of the block, low order byte first. 3. Set byte 8 to the ASCII value ' T ' or ' F ' according to the EncryptMetadata Boolean. 4. Set bytes 9-11 to the ASCII characters ' a ', ' d ', ' b '. 5. Set bytes 12-15 to 4 bytes of random data, which will be ignored. 6. Encrypt the 16-byte block using AES-256 in ECB mode with an initialization vector of zero, using the file encryption key as the key. The result (16 bytes) is stored as the Perms string, and checked for validity when the file is opened. Args: key: p: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. metadata_encrypted: A boolean indicating if the metadata is encrypted. Returns: The perms value
Algorithm 3.10 Computing the encryption dictionary’s Perms (permissions) value
791
821
def compute_Perms_value(key: bytes, p: int, metadata_encrypted: bool) -> bytes: """ Algorithm 3.10 Computing the encryption dictionary’s Perms (permissions) value 1. Extend the permissions (contents of the P integer) to 64 bits by setting the upper 32 bits to all 1’s. (This allows for future extension without changing the format.) 2. Record the 8 bytes of permission in the bytes 0-7 of the block, low order byte first. 3. Set byte 8 to the ASCII value ' T ' or ' F ' according to the EncryptMetadata Boolean. 4. Set bytes 9-11 to the ASCII characters ' a ', ' d ', ' b '. 5. Set bytes 12-15 to 4 bytes of random data, which will be ignored. 6. Encrypt the 16-byte block using AES-256 in ECB mode with an initialization vector of zero, using the file encryption key as the key. The result (16 bytes) is stored as the Perms string, and checked for validity when the file is opened. Args: key: p: A set of flags specifying which operations shall be permitted when the document is opened with user access. If bit 2 is set to 1, all other bits are ignored and all operations are permitted. If bit 2 is set to 0, permission for operations are based on the values of the remaining flags defined in Table 24. metadata_encrypted: A boolean indicating if the metadata is encrypted. Returns: The perms value """ b8 = b"T" if metadata_encrypted else b"F" rr = bytes(random.randrange(0, 256) for _ in range(4)) data = struct.pack("<I", p) + b"\xff\xff\xff\xff" + b8 + b"adb" + rr perms = AES_ECB_encrypt(key, data) return perms
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L791-L821
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 ]
83.870968
[ 26, 27, 28, 29, 30 ]
16.129032
false
71.398747
31
1
83.870968
23
def compute_Perms_value(key: bytes, p: int, metadata_encrypted: bool) -> bytes: b8 = b"T" if metadata_encrypted else b"F" rr = bytes(random.randrange(0, 256) for _ in range(4)) data = struct.pack("<I", p) + b"\xff\xff\xff\xff" + b8 + b"adb" + rr perms = AES_ECB_encrypt(key, data) return perms
24,207
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
Encryption.__init__
( self, algV: int, algR: int, entry: DictionaryObject, first_id_entry: bytes, StmF: str, StrF: str, EFF: str, )
831
854
def __init__( self, algV: int, algR: int, entry: DictionaryObject, first_id_entry: bytes, StmF: str, StrF: str, EFF: str, ) -> None: # See TABLE 3.18 Entries common to all encryption dictionaries self.algV = algV self.algR = algR self.entry = entry self.key_size = entry.get("/Length", 40) self.id1_entry = first_id_entry self.StmF = StmF self.StrF = StrF self.EFF = EFF # 1 => owner password # 2 => user password self._password_type = PasswordType.NOT_DECRYPTED self._key: Optional[bytes] = None
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L831-L854
39
[ 0, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ]
62.5
[]
0
false
71.398747
24
1
100
0
def __init__( self, algV: int, algR: int, entry: DictionaryObject, first_id_entry: bytes, StmF: str, StrF: str, EFF: str, ) -> None: # See TABLE 3.18 Entries common to all encryption dictionaries self.algV = algV self.algR = algR self.entry = entry self.key_size = entry.get("/Length", 40) self.id1_entry = first_id_entry self.StmF = StmF self.StrF = StrF self.EFF = EFF # 1 => owner password # 2 => user password self._password_type = PasswordType.NOT_DECRYPTED self._key: Optional[bytes] = None
24,208
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
Encryption.is_decrypted
(self)
return self._password_type != PasswordType.NOT_DECRYPTED
856
857
def is_decrypted(self) -> bool: return self._password_type != PasswordType.NOT_DECRYPTED
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L856-L857
39
[ 0, 1 ]
100
[]
0
true
71.398747
2
1
100
0
def is_decrypted(self) -> bool: return self._password_type != PasswordType.NOT_DECRYPTED
24,209
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
Encryption.decrypt_object
(self, obj: PdfObject, idnum: int, generation: int)
return cf.decrypt_object(obj)
Algorithm 1: Encryption of data using the RC4 or AES algorithms. a) Obtain the object number and generation number from the object identifier of the string or stream to be encrypted (see 7.3.10, "Indirect Objects"). If the string is a direct object, use the identifier of the indirect object containing it. b) For all strings and streams without crypt filter specifier; treating the object number and generation number as binary integers, extend the original n-byte encryption key to n + 5 bytes by appending the low-order 3 bytes of the object number and the low-order 2 bytes of the generation number in that order, low-order byte first. (n is 5 unless the value of V in the encryption dictionary is greater than 1, in which case n is the value of Length divided by 8.) If using the AES algorithm, extend the encryption key an additional 4 bytes by adding the value “sAlT”, which corresponds to the hexadecimal values 0x73, 0x41, 0x6C, 0x54. (This addition is done for backward compatibility and is not intended to provide additional security.) c) Initialize the MD5 hash function and pass the result of step (b) as input to this function. d) Use the first (n + 5) bytes, up to a maximum of 16, of the output from the MD5 hash as the key for the RC4 or AES symmetric key algorithms, along with the string or stream data to be encrypted. If using the AES algorithm, the Cipher Block Chaining (CBC) mode, which requires an initialization vector, is used. The block size parameter is set to 16 bytes, and the initialization vector is a 16-byte random number that is stored as the first 16 bytes of the encrypted stream or string. Algorithm 3.1a Encryption of data using the AES algorithm 1. Use the 32-byte file encryption key for the AES-256 symmetric key algorithm, along with the string or stream data to be encrypted. Use the AES algorithm in Cipher Block Chaining (CBC) mode, which requires an initialization vector. The block size parameter is set to 16 bytes, and the initialization vector is a 16-byte random number that is stored as the first 16 bytes of the encrypted stream or string. The output is the encrypted data to be stored in the PDF file. Args: obj: idnum: generation: Returns: The PdfObject
Algorithm 1: Encryption of data using the RC4 or AES algorithms.
859
918
def decrypt_object(self, obj: PdfObject, idnum: int, generation: int) -> PdfObject: """ Algorithm 1: Encryption of data using the RC4 or AES algorithms. a) Obtain the object number and generation number from the object identifier of the string or stream to be encrypted (see 7.3.10, "Indirect Objects"). If the string is a direct object, use the identifier of the indirect object containing it. b) For all strings and streams without crypt filter specifier; treating the object number and generation number as binary integers, extend the original n-byte encryption key to n + 5 bytes by appending the low-order 3 bytes of the object number and the low-order 2 bytes of the generation number in that order, low-order byte first. (n is 5 unless the value of V in the encryption dictionary is greater than 1, in which case n is the value of Length divided by 8.) If using the AES algorithm, extend the encryption key an additional 4 bytes by adding the value “sAlT”, which corresponds to the hexadecimal values 0x73, 0x41, 0x6C, 0x54. (This addition is done for backward compatibility and is not intended to provide additional security.) c) Initialize the MD5 hash function and pass the result of step (b) as input to this function. d) Use the first (n + 5) bytes, up to a maximum of 16, of the output from the MD5 hash as the key for the RC4 or AES symmetric key algorithms, along with the string or stream data to be encrypted. If using the AES algorithm, the Cipher Block Chaining (CBC) mode, which requires an initialization vector, is used. The block size parameter is set to 16 bytes, and the initialization vector is a 16-byte random number that is stored as the first 16 bytes of the encrypted stream or string. Algorithm 3.1a Encryption of data using the AES algorithm 1. Use the 32-byte file encryption key for the AES-256 symmetric key algorithm, along with the string or stream data to be encrypted. Use the AES algorithm in Cipher Block Chaining (CBC) mode, which requires an initialization vector. The block size parameter is set to 16 bytes, and the initialization vector is a 16-byte random number that is stored as the first 16 bytes of the encrypted stream or string. The output is the encrypted data to be stored in the PDF file. Args: obj: idnum: generation: Returns: The PdfObject """ pack1 = struct.pack("<i", idnum)[:3] pack2 = struct.pack("<i", generation)[:2] assert self._key key = self._key n = 5 if self.algV == 1 else self.key_size // 8 key_data = key[:n] + pack1 + pack2 key_hash = hashlib.md5(key_data) rc4_key = key_hash.digest()[: min(n + 5, 16)] # for AES-128 key_hash.update(b"sAlT") aes128_key = key_hash.digest()[: min(n + 5, 16)] # for AES-256 aes256_key = key stmCrypt = self._get_crypt(self.StmF, rc4_key, aes128_key, aes256_key) StrCrypt = self._get_crypt(self.StrF, rc4_key, aes128_key, aes256_key) efCrypt = self._get_crypt(self.EFF, rc4_key, aes128_key, aes256_key) cf = CryptFilter(stmCrypt, StrCrypt, efCrypt) return cf.decrypt_object(obj)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L859-L918
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59 ]
100
[]
0
true
71.398747
60
2
100
35
def decrypt_object(self, obj: PdfObject, idnum: int, generation: int) -> PdfObject: pack1 = struct.pack("<i", idnum)[:3] pack2 = struct.pack("<i", generation)[:2] assert self._key key = self._key n = 5 if self.algV == 1 else self.key_size // 8 key_data = key[:n] + pack1 + pack2 key_hash = hashlib.md5(key_data) rc4_key = key_hash.digest()[: min(n + 5, 16)] # for AES-128 key_hash.update(b"sAlT") aes128_key = key_hash.digest()[: min(n + 5, 16)] # for AES-256 aes256_key = key stmCrypt = self._get_crypt(self.StmF, rc4_key, aes128_key, aes256_key) StrCrypt = self._get_crypt(self.StrF, rc4_key, aes128_key, aes256_key) efCrypt = self._get_crypt(self.EFF, rc4_key, aes128_key, aes256_key) cf = CryptFilter(stmCrypt, StrCrypt, efCrypt) return cf.decrypt_object(obj)
24,210
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
Encryption._get_crypt
( method: str, rc4_key: bytes, aes128_key: bytes, aes256_key: bytes )
921
931
def _get_crypt( method: str, rc4_key: bytes, aes128_key: bytes, aes256_key: bytes ) -> CryptBase: if method == "/AESV3": return CryptAES(aes256_key) if method == "/AESV2": return CryptAES(aes128_key) elif method == "/Identity": return CryptIdentity() else: return CryptRC4(rc4_key)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L921-L931
39
[ 0, 3, 5, 6, 7, 10 ]
54.545455
[ 4, 8 ]
18.181818
false
71.398747
11
4
81.818182
0
def _get_crypt( method: str, rc4_key: bytes, aes128_key: bytes, aes256_key: bytes ) -> CryptBase: if method == "/AESV3": return CryptAES(aes256_key) if method == "/AESV2": return CryptAES(aes128_key) elif method == "/Identity": return CryptIdentity() else: return CryptRC4(rc4_key)
24,211
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
Encryption.verify
(self, password: Union[bytes, str])
return rc
933
946
def verify(self, password: Union[bytes, str]) -> PasswordType: if isinstance(password, str): try: pwd = password.encode("latin-1") except Exception: # noqa pwd = password.encode("utf-8") else: pwd = password key, rc = self.verify_v4(pwd) if self.algV <= 4 else self.verify_v5(pwd) if rc != PasswordType.NOT_DECRYPTED: self._password_type = rc self._key = key return rc
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L933-L946
39
[ 0, 1, 2, 3, 7, 8, 9, 10, 11, 12, 13 ]
78.571429
[ 4, 5 ]
14.285714
false
71.398747
14
4
85.714286
0
def verify(self, password: Union[bytes, str]) -> PasswordType: if isinstance(password, str): try: pwd = password.encode("latin-1") except Exception: # noqa pwd = password.encode("utf-8") else: pwd = password key, rc = self.verify_v4(pwd) if self.algV <= 4 else self.verify_v5(pwd) if rc != PasswordType.NOT_DECRYPTED: self._password_type = rc self._key = key return rc
24,212
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
Encryption.verify_v4
(self, password: bytes)
return b"", PasswordType.NOT_DECRYPTED
948
983
def verify_v4(self, password: bytes) -> Tuple[bytes, PasswordType]: R = cast(int, self.entry["/R"]) P = cast(int, self.entry["/P"]) P = (P + 0x100000000) % 0x100000000 # maybe < 0 # make type(metadata_encrypted) == bool em = self.entry.get("/EncryptMetadata") metadata_encrypted = em.value if em else True o_entry = cast(ByteStringObject, self.entry["/O"].get_object()).original_bytes u_entry = cast(ByteStringObject, self.entry["/U"].get_object()).original_bytes # verify owner password first key = AlgV4.verify_owner_password( password, R, self.key_size, o_entry, u_entry, P, self.id1_entry, metadata_encrypted, ) if key: return key, PasswordType.OWNER_PASSWORD key = AlgV4.verify_user_password( password, R, self.key_size, o_entry, u_entry, P, self.id1_entry, metadata_encrypted, ) if key: return key, PasswordType.USER_PASSWORD return b"", PasswordType.NOT_DECRYPTED
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L948-L983
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 21, 22, 23, 33, 34, 35 ]
50
[]
0
false
71.398747
36
3
100
0
def verify_v4(self, password: bytes) -> Tuple[bytes, PasswordType]: R = cast(int, self.entry["/R"]) P = cast(int, self.entry["/P"]) P = (P + 0x100000000) % 0x100000000 # maybe < 0 # make type(metadata_encrypted) == bool em = self.entry.get("/EncryptMetadata") metadata_encrypted = em.value if em else True o_entry = cast(ByteStringObject, self.entry["/O"].get_object()).original_bytes u_entry = cast(ByteStringObject, self.entry["/U"].get_object()).original_bytes # verify owner password first key = AlgV4.verify_owner_password( password, R, self.key_size, o_entry, u_entry, P, self.id1_entry, metadata_encrypted, ) if key: return key, PasswordType.OWNER_PASSWORD key = AlgV4.verify_user_password( password, R, self.key_size, o_entry, u_entry, P, self.id1_entry, metadata_encrypted, ) if key: return key, PasswordType.USER_PASSWORD return b"", PasswordType.NOT_DECRYPTED
24,213
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
Encryption.verify_v5
(self, password: bytes)
return key, rc
985
1,010
def verify_v5(self, password: bytes) -> Tuple[bytes, PasswordType]: # TODO: use SASLprep process o_entry = cast(ByteStringObject, self.entry["/O"].get_object()).original_bytes u_entry = cast(ByteStringObject, self.entry["/U"].get_object()).original_bytes oe_entry = cast(ByteStringObject, self.entry["/OE"].get_object()).original_bytes ue_entry = cast(ByteStringObject, self.entry["/UE"].get_object()).original_bytes # verify owner password first key = AlgV5.verify_owner_password( self.algR, password, o_entry, oe_entry, u_entry ) rc = PasswordType.OWNER_PASSWORD if not key: key = AlgV5.verify_user_password(self.algR, password, u_entry, ue_entry) rc = PasswordType.USER_PASSWORD if not key: return b"", PasswordType.NOT_DECRYPTED # verify Perms perms = cast(ByteStringObject, self.entry["/Perms"].get_object()).original_bytes P = cast(int, self.entry["/P"]) P = (P + 0x100000000) % 0x100000000 # maybe < 0 metadata_encrypted = self.entry.get("/EncryptMetadata", True) if not AlgV5.verify_perms(key, perms, P, metadata_encrypted): logger_warning("ignore '/Perms' verify failed", __name__) return key, rc
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L985-L1010
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13 ]
46.153846
[ 14, 15, 16, 19, 20, 21, 22, 23, 24, 25 ]
38.461538
false
71.398747
26
4
61.538462
0
def verify_v5(self, password: bytes) -> Tuple[bytes, PasswordType]: # TODO: use SASLprep process o_entry = cast(ByteStringObject, self.entry["/O"].get_object()).original_bytes u_entry = cast(ByteStringObject, self.entry["/U"].get_object()).original_bytes oe_entry = cast(ByteStringObject, self.entry["/OE"].get_object()).original_bytes ue_entry = cast(ByteStringObject, self.entry["/UE"].get_object()).original_bytes # verify owner password first key = AlgV5.verify_owner_password( self.algR, password, o_entry, oe_entry, u_entry ) rc = PasswordType.OWNER_PASSWORD if not key: key = AlgV5.verify_user_password(self.algR, password, u_entry, ue_entry) rc = PasswordType.USER_PASSWORD if not key: return b"", PasswordType.NOT_DECRYPTED # verify Perms perms = cast(ByteStringObject, self.entry["/Perms"].get_object()).original_bytes P = cast(int, self.entry["/P"]) P = (P + 0x100000000) % 0x100000000 # maybe < 0 metadata_encrypted = self.entry.get("/EncryptMetadata", True) if not AlgV5.verify_perms(key, perms, P, metadata_encrypted): logger_warning("ignore '/Perms' verify failed", __name__) return key, rc
24,214
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_encryption.py
Encryption.read
(encryption_entry: DictionaryObject, first_id_entry: bytes)
return Encryption(V, R, encryption_entry, first_id_entry, StmF, StrF, EFF)
1,013
1,052
def read(encryption_entry: DictionaryObject, first_id_entry: bytes) -> "Encryption": filter = encryption_entry.get("/Filter") if filter != "/Standard": raise NotImplementedError( "only Standard PDF encryption handler is available" ) if "/SubFilter" in encryption_entry: raise NotImplementedError("/SubFilter NOT supported") StmF = "/V2" StrF = "/V2" EFF = "/V2" V = encryption_entry.get("/V", 0) if V not in (1, 2, 3, 4, 5): raise NotImplementedError(f"Encryption V={V} NOT supported") if V >= 4: filters = encryption_entry["/CF"] StmF = encryption_entry.get("/StmF", "/Identity") StrF = encryption_entry.get("/StrF", "/Identity") EFF = encryption_entry.get("/EFF", StmF) if StmF != "/Identity": StmF = filters[StmF]["/CFM"] # type: ignore if StrF != "/Identity": StrF = filters[StrF]["/CFM"] # type: ignore if EFF != "/Identity": EFF = filters[EFF]["/CFM"] # type: ignore allowed_methods = ("/Identity", "/V2", "/AESV2", "/AESV3") if StmF not in allowed_methods: raise NotImplementedError("StmF Method {StmF} NOT supported!") if StrF not in allowed_methods: raise NotImplementedError(f"StrF Method {StrF} NOT supported!") if EFF not in allowed_methods: raise NotImplementedError(f"EFF Method {EFF} NOT supported!") R = cast(int, encryption_entry["/R"]) return Encryption(V, R, encryption_entry, first_id_entry, StmF, StrF, EFF)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_encryption.py#L1013-L1052
39
[ 0, 1, 2, 6, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33, 35, 37, 38, 39 ]
94.117647
[]
0
false
71.398747
40
11
100
0
def read(encryption_entry: DictionaryObject, first_id_entry: bytes) -> "Encryption": filter = encryption_entry.get("/Filter") if filter != "/Standard": raise NotImplementedError( "only Standard PDF encryption handler is available" ) if "/SubFilter" in encryption_entry: raise NotImplementedError("/SubFilter NOT supported") StmF = "/V2" StrF = "/V2" EFF = "/V2" V = encryption_entry.get("/V", 0) if V not in (1, 2, 3, 4, 5): raise NotImplementedError(f"Encryption V={V} NOT supported") if V >= 4: filters = encryption_entry["/CF"] StmF = encryption_entry.get("/StmF", "/Identity") StrF = encryption_entry.get("/StrF", "/Identity") EFF = encryption_entry.get("/EFF", StmF) if StmF != "/Identity": StmF = filters[StmF]["/CFM"] # type: ignore if StrF != "/Identity": StrF = filters[StrF]["/CFM"] # type: ignore if EFF != "/Identity": EFF = filters[EFF]["/CFM"] # type: ignore allowed_methods = ("/Identity", "/V2", "/AESV2", "/AESV3") if StmF not in allowed_methods: raise NotImplementedError("StmF Method {StmF} NOT supported!") if StrF not in allowed_methods: raise NotImplementedError(f"StrF Method {StrF} NOT supported!") if EFF not in allowed_methods: raise NotImplementedError(f"EFF Method {EFF} NOT supported!") R = cast(int, encryption_entry["/R"]) return Encryption(V, R, encryption_entry, first_id_entry, StmF, StrF, EFF)
24,215
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/constants.py
FieldDictionaryAttributes.attributes
(cls)
return ( cls.TM, cls.T, cls.FT, cls.Parent, cls.TU, cls.Ff, cls.V, cls.DV, cls.Kids, cls.AA, )
308
320
def attributes(cls) -> Tuple[str, ...]: return ( cls.TM, cls.T, cls.FT, cls.Parent, cls.TU, cls.Ff, cls.V, cls.DV, cls.Kids, cls.AA, )
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/constants.py#L308-L320
39
[ 0, 1 ]
15.384615
[]
0
false
100
13
1
100
0
def attributes(cls) -> Tuple[str, ...]: return ( cls.TM, cls.T, cls.FT, cls.Parent, cls.TU, cls.Ff, cls.V, cls.DV, cls.Kids, cls.AA, )
24,216
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/constants.py
FieldDictionaryAttributes.attributes_dict
(cls)
return { cls.FT: "Field Type", cls.Parent: "Parent", cls.T: "Field Name", cls.TU: "Alternate Field Name", cls.TM: "Mapping Name", cls.Ff: "Field Flags", cls.V: "Value", cls.DV: "Default Value", }
323
333
def attributes_dict(cls) -> Dict[str, str]: return { cls.FT: "Field Type", cls.Parent: "Parent", cls.T: "Field Name", cls.TU: "Alternate Field Name", cls.TM: "Mapping Name", cls.Ff: "Field Flags", cls.V: "Value", cls.DV: "Default Value", }
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/constants.py#L323-L333
39
[ 0, 1 ]
18.181818
[]
0
false
100
11
1
100
0
def attributes_dict(cls) -> Dict[str, str]: return { cls.FT: "Field Type", cls.Parent: "Parent", cls.T: "Field Name", cls.TU: "Alternate Field Name", cls.TM: "Mapping Name", cls.Ff: "Field Flags", cls.V: "Value", cls.DV: "Default Value", }
24,217
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/constants.py
CheckboxRadioButtonAttributes.attributes
(cls)
return (cls.Opt,)
342
343
def attributes(cls) -> Tuple[str, ...]: return (cls.Opt,)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/constants.py#L342-L343
39
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def attributes(cls) -> Tuple[str, ...]: return (cls.Opt,)
24,218
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/constants.py
CheckboxRadioButtonAttributes.attributes_dict
(cls)
return { cls.Opt: "Options", }
346
349
def attributes_dict(cls) -> Dict[str, str]: return { cls.Opt: "Options", }
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/constants.py#L346-L349
39
[ 0, 1 ]
50
[]
0
false
100
4
1
100
0
def attributes_dict(cls) -> Dict[str, str]: return { cls.Opt: "Options", }
24,219
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
_get_max_pdf_version_header
(header1: bytes, header2: bytes)
return versions[max(pdf_header_indices)]
79
95
def _get_max_pdf_version_header(header1: bytes, header2: bytes) -> bytes: versions = ( b"%PDF-1.3", b"%PDF-1.4", b"%PDF-1.5", b"%PDF-1.6", b"%PDF-1.7", b"%PDF-2.0", ) pdf_header_indices = [] if header1 in versions: pdf_header_indices.append(versions.index(header1)) if header2 in versions: pdf_header_indices.append(versions.index(header2)) if len(pdf_header_indices) == 0: raise ValueError(f"neither {header1!r} nor {header2!r} are proper headers") return versions[max(pdf_header_indices)]
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L79-L95
39
[ 0, 1, 9, 10, 11, 12, 13, 14, 15, 16 ]
58.823529
[]
0
false
97.416974
17
4
100
0
def _get_max_pdf_version_header(header1: bytes, header2: bytes) -> bytes: versions = ( b"%PDF-1.3", b"%PDF-1.4", b"%PDF-1.5", b"%PDF-1.6", b"%PDF-1.7", b"%PDF-2.0", ) pdf_header_indices = [] if header1 in versions: pdf_header_indices.append(versions.index(header1)) if header2 in versions: pdf_header_indices.append(versions.index(header2)) if len(pdf_header_indices) == 0: raise ValueError(f"neither {header1!r} nor {header2!r} are proper headers") return versions[max(pdf_header_indices)]
24,220
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
read_until_whitespace
(stream: StreamType, maxchars: Optional[int] = None)
return txt
Read non-whitespace characters and return them. Stops upon encountering whitespace or when maxchars is reached. Args: stream: The data stream from which was read. maxchars: The maximum number of bytes returned; by default unlimited. Returns: The data which was read.
Read non-whitespace characters and return them.
98
119
def read_until_whitespace(stream: StreamType, maxchars: Optional[int] = None) -> bytes: """ Read non-whitespace characters and return them. Stops upon encountering whitespace or when maxchars is reached. Args: stream: The data stream from which was read. maxchars: The maximum number of bytes returned; by default unlimited. Returns: The data which was read. """ txt = b"" while True: tok = stream.read(1) if tok.isspace() or not tok: break txt += tok if len(txt) == maxchars: break return txt
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L98-L119
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ]
100
[]
0
true
97.416974
22
5
100
10
def read_until_whitespace(stream: StreamType, maxchars: Optional[int] = None) -> bytes: txt = b"" while True: tok = stream.read(1) if tok.isspace() or not tok: break txt += tok if len(txt) == maxchars: break return txt
24,221
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
read_non_whitespace
(stream: StreamType)
return tok
Find and read the next non-whitespace character (ignores whitespace). Args: stream: The data stream from which was read. Returns: The data which was read.
Find and read the next non-whitespace character (ignores whitespace).
122
135
def read_non_whitespace(stream: StreamType) -> bytes: """ Find and read the next non-whitespace character (ignores whitespace). Args: stream: The data stream from which was read. Returns: The data which was read. """ tok = stream.read(1) while tok in WHITESPACES: tok = stream.read(1) return tok
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L122-L135
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
97.416974
14
2
100
7
def read_non_whitespace(stream: StreamType) -> bytes: tok = stream.read(1) while tok in WHITESPACES: tok = stream.read(1) return tok
24,222
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
skip_over_whitespace
(stream: StreamType)
return cnt > 1
Similar to read_non_whitespace, but return a boolean if more than one whitespace character was read. Args: stream: The data stream from which was read. Returns: True if more than one whitespace was skipped, otherwise return False.
Similar to read_non_whitespace, but return a boolean if more than one whitespace character was read.
138
155
def skip_over_whitespace(stream: StreamType) -> bool: """ Similar to read_non_whitespace, but return a boolean if more than one whitespace character was read. Args: stream: The data stream from which was read. Returns: True if more than one whitespace was skipped, otherwise return False. """ tok = WHITESPACES[0] cnt = 0 while tok in WHITESPACES: tok = stream.read(1) cnt += 1 return cnt > 1
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L138-L155
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
100
[]
0
true
97.416974
18
2
100
9
def skip_over_whitespace(stream: StreamType) -> bool: tok = WHITESPACES[0] cnt = 0 while tok in WHITESPACES: tok = stream.read(1) cnt += 1 return cnt > 1
24,223
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
skip_over_comment
(stream: StreamType)
158
163
def skip_over_comment(stream: StreamType) -> None: tok = stream.read(1) stream.seek(-1, 1) if tok == b"%": while tok not in (b"\n", b"\r"): tok = stream.read(1)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L158-L163
39
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
97.416974
6
3
100
0
def skip_over_comment(stream: StreamType) -> None: tok = stream.read(1) stream.seek(-1, 1) if tok == b"%": while tok not in (b"\n", b"\r"): tok = stream.read(1)
24,224
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
read_until_regex
( stream: StreamType, regex: Pattern[bytes], ignore_eof: bool = False )
return name
Read until the regular expression pattern matched (ignore the match). Args: ignore_eof: If true, ignore end-of-line and return immediately regex: re.Pattern ignore_eof: (Default value = False) Returns: The read bytes. Raises: PdfStreamError: on premature end-of-file
Read until the regular expression pattern matched (ignore the match).
166
197
def read_until_regex( stream: StreamType, regex: Pattern[bytes], ignore_eof: bool = False ) -> bytes: """ Read until the regular expression pattern matched (ignore the match). Args: ignore_eof: If true, ignore end-of-line and return immediately regex: re.Pattern ignore_eof: (Default value = False) Returns: The read bytes. Raises: PdfStreamError: on premature end-of-file """ name = b"" while True: tok = stream.read(16) if not tok: if ignore_eof: return name raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY) m = regex.search(tok) if m is not None: name += tok[: m.start()] stream.seek(m.start() - len(tok), 1) break name += tok return name
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L166-L197
39
[ 0, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ]
50
[]
0
false
97.416974
32
5
100
12
def read_until_regex( stream: StreamType, regex: Pattern[bytes], ignore_eof: bool = False ) -> bytes: name = b"" while True: tok = stream.read(16) if not tok: if ignore_eof: return name raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY) m = regex.search(tok) if m is not None: name += tok[: m.start()] stream.seek(m.start() - len(tok), 1) break name += tok return name
24,225
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
read_block_backwards
(stream: StreamType, to_read: int)
return read
Given a stream at position X, read a block of size to_read ending at position X. This changes the stream's position to the beginning of where the block was read. Args: stream: to_read: Returns: The data which was read.
Given a stream at position X, read a block of size to_read ending at position X.
200
221
def read_block_backwards(stream: StreamType, to_read: int) -> bytes: """ Given a stream at position X, read a block of size to_read ending at position X. This changes the stream's position to the beginning of where the block was read. Args: stream: to_read: Returns: The data which was read. """ if stream.tell() < to_read: raise PdfStreamError("Could not read malformed PDF file") # Seek to the start of the block we want to read. stream.seek(-to_read, SEEK_CUR) read = stream.read(to_read) # Seek to the start of the block we read after reading it. stream.seek(-to_read, SEEK_CUR) return read
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L200-L221
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ]
100
[]
0
true
97.416974
22
2
100
11
def read_block_backwards(stream: StreamType, to_read: int) -> bytes: if stream.tell() < to_read: raise PdfStreamError("Could not read malformed PDF file") # Seek to the start of the block we want to read. stream.seek(-to_read, SEEK_CUR) read = stream.read(to_read) # Seek to the start of the block we read after reading it. stream.seek(-to_read, SEEK_CUR) return read
24,226
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
read_previous_line
(stream: StreamType)
return b"".join(line_content[::-1])
Given a byte stream with current position X, return the previous line. All characters between the first CR/LF byte found before X (or, the start of the file, if no such byte is found) and position X After this call, the stream will be positioned one byte after the first non-CRLF character found beyond the first CR/LF byte before X, or, if no such byte is found, at the beginning of the stream. Args: stream: StreamType: Returns: The data which was read.
Given a byte stream with current position X, return the previous line.
224
278
def read_previous_line(stream: StreamType) -> bytes: """ Given a byte stream with current position X, return the previous line. All characters between the first CR/LF byte found before X (or, the start of the file, if no such byte is found) and position X After this call, the stream will be positioned one byte after the first non-CRLF character found beyond the first CR/LF byte before X, or, if no such byte is found, at the beginning of the stream. Args: stream: StreamType: Returns: The data which was read. """ line_content = [] found_crlf = False if stream.tell() == 0: raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY) while True: to_read = min(DEFAULT_BUFFER_SIZE, stream.tell()) if to_read == 0: break # Read the block. After this, our stream will be one # beyond the initial position. block = read_block_backwards(stream, to_read) idx = len(block) - 1 if not found_crlf: # We haven't found our first CR/LF yet. # Read off characters until we hit one. while idx >= 0 and block[idx] not in b"\r\n": idx -= 1 if idx >= 0: found_crlf = True if found_crlf: # We found our first CR/LF already (on this block or # a previous one). # Our combined line is the remainder of the block # plus any previously read blocks. line_content.append(block[idx + 1 :]) # Continue to read off any more CRLF characters. while idx >= 0 and block[idx] in b"\r\n": idx -= 1 else: # Didn't find CR/LF yet - add this block to our # previously read blocks and continue. line_content.append(block) if idx >= 0: # We found the next non-CRLF character. # Set the stream position correctly, then break stream.seek(idx + 1, SEEK_CUR) break # Join all the blocks in the line (which are in reverse order) return b"".join(line_content[::-1])
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L224-L278
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54 ]
100
[]
0
true
97.416974
55
12
100
13
def read_previous_line(stream: StreamType) -> bytes: line_content = [] found_crlf = False if stream.tell() == 0: raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY) while True: to_read = min(DEFAULT_BUFFER_SIZE, stream.tell()) if to_read == 0: break # Read the block. After this, our stream will be one # beyond the initial position. block = read_block_backwards(stream, to_read) idx = len(block) - 1 if not found_crlf: # We haven't found our first CR/LF yet. # Read off characters until we hit one. while idx >= 0 and block[idx] not in b"\r\n": idx -= 1 if idx >= 0: found_crlf = True if found_crlf: # We found our first CR/LF already (on this block or # a previous one). # Our combined line is the remainder of the block # plus any previously read blocks. line_content.append(block[idx + 1 :]) # Continue to read off any more CRLF characters. while idx >= 0 and block[idx] in b"\r\n": idx -= 1 else: # Didn't find CR/LF yet - add this block to our # previously read blocks and continue. line_content.append(block) if idx >= 0: # We found the next non-CRLF character. # Set the stream position correctly, then break stream.seek(idx + 1, SEEK_CUR) break # Join all the blocks in the line (which are in reverse order) return b"".join(line_content[::-1])
24,227
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
matrix_multiply
( a: TransformationMatrixType, b: TransformationMatrixType )
return tuple( # type: ignore[return-value] tuple(sum(float(i) * float(j) for i, j in zip(row, col)) for col in zip(*b)) for row in a )
281
287
def matrix_multiply( a: TransformationMatrixType, b: TransformationMatrixType ) -> TransformationMatrixType: return tuple( # type: ignore[return-value] tuple(sum(float(i) * float(j) for i, j in zip(row, col)) for col in zip(*b)) for row in a )
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L281-L287
39
[ 0, 3 ]
28.571429
[]
0
false
97.416974
7
1
100
0
def matrix_multiply( a: TransformationMatrixType, b: TransformationMatrixType ) -> TransformationMatrixType: return tuple( # type: ignore[return-value] tuple(sum(float(i) * float(j) for i, j in zip(row, col)) for col in zip(*b)) for row in a )
24,228
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
mark_location
(stream: StreamType)
Create text file showing current location in context.
Create text file showing current location in context.
290
299
def mark_location(stream: StreamType) -> None: """Create text file showing current location in context.""" # Mainly for debugging radius = 5000 stream.seek(-radius, 1) with open("pypdf_pdfLocation.txt", "wb") as output_fh: output_fh.write(stream.read(radius)) output_fh.write(b"HERE") output_fh.write(stream.read(radius)) stream.seek(-radius, 1)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L290-L299
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
97.416974
10
2
100
1
def mark_location(stream: StreamType) -> None: # Mainly for debugging radius = 5000 stream.seek(-radius, 1) with open("pypdf_pdfLocation.txt", "wb") as output_fh: output_fh.write(stream.read(radius)) output_fh.write(b"HERE") output_fh.write(stream.read(radius)) stream.seek(-radius, 1)
24,229
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
b_
(s: Union[str, bytes])
305
320
def b_(s: Union[str, bytes]) -> bytes: bc = B_CACHE if s in bc: return bc[s] if isinstance(s, bytes): return s try: r = s.encode("latin-1") if len(s) < 2: bc[s] = r return r except Exception: r = s.encode("utf-8") if len(s) < 2: bc[s] = r return r
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L305-L320
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
97.416974
16
6
100
0
def b_(s: Union[str, bytes]) -> bytes: bc = B_CACHE if s in bc: return bc[s] if isinstance(s, bytes): return s try: r = s.encode("latin-1") if len(s) < 2: bc[s] = r return r except Exception: r = s.encode("utf-8") if len(s) < 2: bc[s] = r return r
24,230
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
str_
(b: str)
324
325
def str_(b: str) -> str: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L324-L325
39
[]
0
[]
0
false
97.416974
2
1
100
0
def str_(b: str) -> str: ...
24,231
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
str_
(b: bytes)
329
330
def str_(b: bytes) -> str: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L329-L330
39
[]
0
[]
0
false
97.416974
2
1
100
0
def str_(b: bytes) -> str: ...
24,232
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
str_
(b: Union[str, bytes])
333
337
def str_(b: Union[str, bytes]) -> str: if isinstance(b, bytes): return b.decode("latin-1") else: return b
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L333-L337
39
[ 0, 1, 2, 4 ]
80
[]
0
false
97.416974
5
2
100
0
def str_(b: Union[str, bytes]) -> str: if isinstance(b, bytes): return b.decode("latin-1") else: return b
24,233
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
ord_
(b: str)
341
342
def ord_(b: str) -> int: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L341-L342
39
[]
0
[]
0
false
97.416974
2
1
100
0
def ord_(b: str) -> int: ...
24,234
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
ord_
(b: bytes)
346
347
def ord_(b: bytes) -> bytes: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L346-L347
39
[]
0
[]
0
false
97.416974
2
1
100
0
def ord_(b: bytes) -> bytes: ...
24,235
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
ord_
(b: int)
351
352
def ord_(b: int) -> int: ...
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L351-L352
39
[]
0
[]
0
false
97.416974
2
1
100
0
def ord_(b: int) -> int: ...
24,236
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
ord_
(b: Union[int, str, bytes])
return b
355
358
def ord_(b: Union[int, str, bytes]) -> Union[int, bytes]: if isinstance(b, str): return ord(b) return b
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L355-L358
39
[ 0, 1, 2, 3 ]
100
[]
0
true
97.416974
4
2
100
0
def ord_(b: Union[int, str, bytes]) -> Union[int, bytes]: if isinstance(b, str): return ord(b) return b
24,237
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
hexencode
(b: bytes)
return coded[0]
361
365
def hexencode(b: bytes) -> bytes: coder = getencoder("hex_codec") coded = coder(b) # type: ignore return coded[0]
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L361-L365
39
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
97.416974
5
1
100
0
def hexencode(b: bytes) -> bytes: coder = getencoder("hex_codec") coded = coder(b) # type: ignore return coded[0]
24,238
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
hex_str
(num: int)
return hex(num).replace("L", "")
368
369
def hex_str(num: int) -> str: return hex(num).replace("L", "")
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L368-L369
39
[ 0, 1 ]
100
[]
0
true
97.416974
2
1
100
0
def hex_str(num: int) -> str: return hex(num).replace("L", "")
24,239
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
paeth_predictor
(left: int, up: int, up_left: int)
375
386
def paeth_predictor(left: int, up: int, up_left: int) -> int: p = left + up - up_left dist_left = abs(p - left) dist_up = abs(p - up) dist_up_left = abs(p - up_left) if dist_left <= dist_up and dist_left <= dist_up_left: return left elif dist_up <= dist_up_left: return up else: return up_left
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L375-L386
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11 ]
91.666667
[]
0
false
97.416974
12
4
100
0
def paeth_predictor(left: int, up: int, up_left: int) -> int: p = left + up - up_left dist_left = abs(p - left) dist_up = abs(p - up) dist_up_left = abs(p - up_left) if dist_left <= dist_up and dist_left <= dist_up_left: return left elif dist_up <= dist_up_left: return up else: return up_left
24,240
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
deprecate
(msg: str, stacklevel: int = 3)
389
390
def deprecate(msg: str, stacklevel: int = 3) -> None: warnings.warn(msg, DeprecationWarning, stacklevel=stacklevel)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L389-L390
39
[ 0, 1 ]
100
[]
0
true
97.416974
2
1
100
0
def deprecate(msg: str, stacklevel: int = 3) -> None: warnings.warn(msg, DeprecationWarning, stacklevel=stacklevel)
24,241
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
deprecate_with_replacement
( old_name: str, new_name: str, removed_in: str = "3.0.0" )
Raise an exception that a feature will be removed, but has a replacement.
Raise an exception that a feature will be removed, but has a replacement.
397
403
def deprecate_with_replacement( old_name: str, new_name: str, removed_in: str = "3.0.0" ) -> None: """ Raise an exception that a feature will be removed, but has a replacement. """ deprecate(DEPR_MSG.format(old_name, new_name, removed_in), 4)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L397-L403
39
[ 0 ]
14.285714
[ 6 ]
14.285714
false
97.416974
7
1
85.714286
1
def deprecate_with_replacement( old_name: str, new_name: str, removed_in: str = "3.0.0" ) -> None: deprecate(DEPR_MSG.format(old_name, new_name, removed_in), 4)
24,242
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
deprecation_with_replacement
( old_name: str, new_name: str, removed_in: str = "3.0.0" )
Raise an exception that a feature was already removed, but has a replacement.
Raise an exception that a feature was already removed, but has a replacement.
406
412
def deprecation_with_replacement( old_name: str, new_name: str, removed_in: str = "3.0.0" ) -> None: """ Raise an exception that a feature was already removed, but has a replacement. """ deprecation(DEPR_MSG_HAPPENED.format(old_name, removed_in, new_name))
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L406-L412
39
[ 0, 5, 6 ]
42.857143
[]
0
false
97.416974
7
1
100
1
def deprecation_with_replacement( old_name: str, new_name: str, removed_in: str = "3.0.0" ) -> None: deprecation(DEPR_MSG_HAPPENED.format(old_name, removed_in, new_name))
24,243
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
deprecate_no_replacement
(name: str, removed_in: str = "3.0.0")
Raise an exception that a feature will be removed without replacement.
Raise an exception that a feature will be removed without replacement.
415
419
def deprecate_no_replacement(name: str, removed_in: str = "3.0.0") -> None: """ Raise an exception that a feature will be removed without replacement. """ deprecate(DEPR_MSG_NO_REPLACEMENT.format(name, removed_in), 4)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L415-L419
39
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
97.416974
5
1
100
1
def deprecate_no_replacement(name: str, removed_in: str = "3.0.0") -> None: deprecate(DEPR_MSG_NO_REPLACEMENT.format(name, removed_in), 4)
24,244
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
deprecation_no_replacement
(name: str, removed_in: str = "3.0.0")
Raise an exception that a feature was already removed without replacement.
Raise an exception that a feature was already removed without replacement.
422
426
def deprecation_no_replacement(name: str, removed_in: str = "3.0.0") -> None: """ Raise an exception that a feature was already removed without replacement. """ deprecation(DEPR_MSG_NO_REPLACEMENT_HAPPENED.format(name, removed_in))
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L422-L426
39
[ 0, 1, 2, 3 ]
80
[ 4 ]
20
false
97.416974
5
1
80
1
def deprecation_no_replacement(name: str, removed_in: str = "3.0.0") -> None: deprecation(DEPR_MSG_NO_REPLACEMENT_HAPPENED.format(name, removed_in))
24,245
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
logger_warning
(msg: str, src: str)
Use this instead of logger.warning directly. That allows people to overwrite it more easily. ## Exception, warnings.warn, logger_warning - Exceptions should be used if the user should write code that deals with an error case, e.g. the PDF being completely broken. - warnings.warn should be used if the user needs to fix their code, e.g. DeprecationWarnings - logger_warning should be used if the user needs to know that an issue was handled by pypdf, e.g. a non-compliant PDF being read in a way that pypdf could apply a robustness fix to still read it. This applies mainly to strict=False mode.
Use this instead of logger.warning directly.
429
445
def logger_warning(msg: str, src: str) -> None: """ Use this instead of logger.warning directly. That allows people to overwrite it more easily. ## Exception, warnings.warn, logger_warning - Exceptions should be used if the user should write code that deals with an error case, e.g. the PDF being completely broken. - warnings.warn should be used if the user needs to fix their code, e.g. DeprecationWarnings - logger_warning should be used if the user needs to know that an issue was handled by pypdf, e.g. a non-compliant PDF being read in a way that pypdf could apply a robustness fix to still read it. This applies mainly to strict=False mode. """ logging.getLogger(src).warning(msg)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L429-L445
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
100
[]
0
true
97.416974
17
1
100
13
def logger_warning(msg: str, src: str) -> None: logging.getLogger(src).warning(msg)
24,246
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
deprecation_bookmark
(**aliases: str)
return decoration
Decorator for deprecated term "bookmark" To be used for methods and function arguments outline_item = a bookmark outline = a collection of outline items
Decorator for deprecated term "bookmark" To be used for methods and function arguments outline_item = a bookmark outline = a collection of outline items
448
464
def deprecation_bookmark(**aliases: str) -> Callable: """ Decorator for deprecated term "bookmark" To be used for methods and function arguments outline_item = a bookmark outline = a collection of outline items """ def decoration(func: Callable): # type: ignore @functools.wraps(func) def wrapper(*args, **kwargs): # type: ignore rename_kwargs(func.__name__, kwargs, aliases, fail=True) return func(*args, **kwargs) return wrapper return decoration
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L448-L464
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
106.25
[]
0
true
97.416974
17
3
100
4
def deprecation_bookmark(**aliases: str) -> Callable: def decoration(func: Callable): # type: ignore @functools.wraps(func) def wrapper(*args, **kwargs): # type: ignore rename_kwargs(func.__name__, kwargs, aliases, fail=True) return func(*args, **kwargs) return wrapper return decoration
24,247
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
rename_kwargs
( # type: ignore func_name: str, kwargs: Dict[str, Any], aliases: Dict[str, str], fail: bool = False )
Helper function to deprecate arguments.
Helper function to deprecate arguments.
467
491
def rename_kwargs( # type: ignore func_name: str, kwargs: Dict[str, Any], aliases: Dict[str, str], fail: bool = False ): """ Helper function to deprecate arguments. """ for old_term, new_term in aliases.items(): if old_term in kwargs: if fail: raise DeprecationError( f"{old_term} is deprecated as an argument. Use {new_term} instead" ) if new_term in kwargs: raise TypeError( f"{func_name} received both {old_term} and {new_term} as an argument. " f"{old_term} is deprecated. Use {new_term} instead." ) kwargs[new_term] = kwargs.pop(old_term) warnings.warn( message=( f"{old_term} is deprecated as an argument. Use {new_term} instead" ), category=DeprecationWarning, )
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L467-L491
39
[ 0, 6, 7, 8, 9 ]
22.727273
[ 13, 18 ]
9.090909
false
97.416974
25
5
90.909091
1
def rename_kwargs( # type: ignore func_name: str, kwargs: Dict[str, Any], aliases: Dict[str, str], fail: bool = False ): for old_term, new_term in aliases.items(): if old_term in kwargs: if fail: raise DeprecationError( f"{old_term} is deprecated as an argument. Use {new_term} instead" ) if new_term in kwargs: raise TypeError( f"{func_name} received both {old_term} and {new_term} as an argument. " f"{old_term} is deprecated. Use {new_term} instead." ) kwargs[new_term] = kwargs.pop(old_term) warnings.warn( message=( f"{old_term} is deprecated as an argument. Use {new_term} instead" ), category=DeprecationWarning, )
24,248
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_utils.py
_human_readable_bytes
(bytes: int)
494
502
def _human_readable_bytes(bytes: int) -> str: if bytes < 10**3: return f"{bytes} Byte" elif bytes < 10**6: return f"{bytes / 10**3:.1f} kB" elif bytes < 10**9: return f"{bytes / 10**6:.1f} MB" else: return f"{bytes / 10**9:.1f} GB"
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_utils.py#L494-L502
39
[ 0, 1, 2, 3, 4, 5, 6, 8 ]
88.888889
[]
0
false
97.416974
9
4
100
0
def _human_readable_bytes(bytes: int) -> str: if bytes < 10**3: return f"{bytes} Byte" elif bytes < 10**6: return f"{bytes / 10**3:.1f} kB" elif bytes < 10**9: return f"{bytes / 10**6:.1f} MB" else: return f"{bytes / 10**9:.1f} GB"
24,249
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_writer.py
__init__
(self, fileobj: StrByteType = "")
140
178
def __init__(self, fileobj: StrByteType = "") -> None: self._header = b"%PDF-1.3" self._objects: List[PdfObject] = [] # array of indirect objects self._idnum_hash: Dict[bytes, IndirectObject] = {} self._id_translated: Dict[int, Dict[int, int]] = {} # The root of our page tree node. pages = DictionaryObject() pages.update( { NameObject(PA.TYPE): NameObject("/Pages"), NameObject(PA.COUNT): NumberObject(0), NameObject(PA.KIDS): ArrayObject(), } ) self._pages = self._add_object(pages) # info object info = DictionaryObject() info.update( { NameObject("/Producer"): create_string_object( codecs.BOM_UTF16_BE + "pypdf".encode("utf-16be") ) } ) self._info = self._add_object(info) # root object self._root_object = DictionaryObject() self._root_object.update( { NameObject(PA.TYPE): NameObject(CO.CATALOG), NameObject(CO.PAGES): self._pages, } ) self._root = self._add_object(self._root_object) self.fileobj = fileobj self.with_as_usage = False
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L140-L178
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 15, 16, 17, 18, 19, 26, 27, 28, 29, 30, 36, 37, 38 ]
56.410256
[]
0
false
85.547144
39
1
100
0
def __init__(self, fileobj: StrByteType = "") -> None: self._header = b"%PDF-1.3" self._objects: List[PdfObject] = [] # array of indirect objects self._idnum_hash: Dict[bytes, IndirectObject] = {} self._id_translated: Dict[int, Dict[int, int]] = {} # The root of our page tree node. pages = DictionaryObject() pages.update( { NameObject(PA.TYPE): NameObject("/Pages"), NameObject(PA.COUNT): NumberObject(0), NameObject(PA.KIDS): ArrayObject(), } ) self._pages = self._add_object(pages) # info object info = DictionaryObject() info.update( { NameObject("/Producer"): create_string_object( codecs.BOM_UTF16_BE + "pypdf".encode("utf-16be") ) } ) self._info = self._add_object(info) # root object self._root_object = DictionaryObject() self._root_object.update( { NameObject(PA.TYPE): NameObject(CO.CATALOG), NameObject(CO.PAGES): self._pages, } ) self._root = self._add_object(self._root_object) self.fileobj = fileobj self.with_as_usage = False
24,250
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_writer.py
__enter__
(self)
return self
Store that writer is initialized by 'with'.
Store that writer is initialized by 'with'.
180
183
def __enter__(self) -> "PdfWriter": """Store that writer is initialized by 'with'.""" self.with_as_usage = True return self
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L180-L183
39
[ 0, 1, 2, 3 ]
100
[]
0
true
85.547144
4
1
100
1
def __enter__(self) -> "PdfWriter": self.with_as_usage = True return self
24,251
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_writer.py
__exit__
( self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], traceback: Optional[TracebackType], )
Write data to the fileobj.
Write data to the fileobj.
185
193
def __exit__( self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], traceback: Optional[TracebackType], ) -> None: """Write data to the fileobj.""" if self.fileobj: self.write(self.fileobj)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L185-L193
39
[ 0, 6, 7, 8 ]
44.444444
[]
0
false
85.547144
9
2
100
1
def __exit__( self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], traceback: Optional[TracebackType], ) -> None: if self.fileobj: self.write(self.fileobj)
24,252
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_writer.py
pdf_header
(self)
return self._header
Header of the PDF document that is written. This should be something like ``b'%PDF-1.5'``. It is recommended to set the lowest version that supports all features which are used within the PDF file.
Header of the PDF document that is written.
196
204
def pdf_header(self) -> bytes: """ Header of the PDF document that is written. This should be something like ``b'%PDF-1.5'``. It is recommended to set the lowest version that supports all features which are used within the PDF file. """ return self._header
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L196-L204
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
85.547144
9
1
100
5
def pdf_header(self) -> bytes: return self._header
24,253