Seregon/PkgToolBox

Toolbox for analyzing and editing pkg application files for psp,ps3, ps4 and ps5, includes the most useful functions you might need.

Python/57.3 KB/No license
Utilities/utils.py
PkgToolBox / Utilities / utils.py
1import os
2import struct
3import io
4import zipfile
5import enum
6import shutil
7from typing import List
8
9class EndianType(enum.Enum):
10 BigEndian = 'big'
11 LittleEndian = 'little'
12
13
14class Utils:
15 @staticmethod
16 def hex2binary(hex_str: str) -> bytes:
17 return bytes.fromhex(hex_str)
18
19 @staticmethod
20 def hex_to_dec(hex_bytes: bytes, reverse: str = "") -> int:
21 if reverse == "reverse":
22 hex_bytes = hex_bytes[::-1]
23 return int.from_bytes(hex_bytes, byteorder='big')
24
25 @staticmethod
26 def read_write_data(file_to_use: str, file_to_use2: str = "", method_read_or_write_or_both: str = "", method_binary_or_integer: str = "", bin_data: bytes = None, bin_data2: int = 0, offset: int = 0, count: int = 0):
27 if method_read_or_write_or_both == "r":
28 with open(file_to_use, 'rb') as f:
29 read_buffer = f.read()
30 return read_buffer
31 elif method_read_or_write_or_both == "w":
32 with open(file_to_use, 'ab') as f:
33 if method_binary_or_integer == "bi":
34 f.write(bin_data)
35 elif method_binary_or_integer == "in":
36 f.write(struct.pack('i', bin_data2))
37 elif method_read_or_write_or_both == "b":
38 with open(file_to_use, 'rb') as fr, open(file_to_use2, 'ab') as fw:
39 fr.seek(offset)
40 buffer_size = 4096
41 while count > 0:
42 buffer = fr.read(min(buffer_size, count))
43 if not buffer:
44 break
45 fw.write(buffer)
46 count -= len(buffer)
47
48 @staticmethod
49 def compare_bytes(a: bytes, b: bytes) -> bool:
50 return a == b
51
52 @staticmethod
53 def extract_file_to_directory(zip_file_name: str, output_directory: str):
54 with zipfile.ZipFile(zip_file_name, 'r') as zip_ref:
55 zip_ref.extractall(output_directory)
56
57 @staticmethod
58 def byte_to_string(buff: bytes) -> str:
59 return buff.hex().upper()
60
61 @staticmethod
62 def generate_stream_from_string(s: str) -> io.BytesIO:
63 return io.BytesIO(s.encode())
64
65 @staticmethod
66 def read_uint32(stream: io.BytesIO) -> int:
67 return struct.unpack('<I', stream.read(4))[0]
68
69 @staticmethod
70 def read_uint16(stream: io.BytesIO) -> int:
71 return struct.unpack('<H', stream.read(2))[0]
72
73 @staticmethod
74 def read_ascii_string(stream: io.BytesIO, length: int) -> str:
75 return stream.read(length).decode('ascii')
76
77 @staticmethod
78 def read_utf8_string(stream: io.BytesIO, length: int) -> str:
79 return stream.read(length).decode('utf-8')
80
81 @staticmethod
82 def read_byte(stream: io.BytesIO, length: int) -> bytes:
83 return stream.read(length)