Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Bigint.pack for odd-length hex integers #58

Merged
merged 2 commits into from
Mar 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions malduck/string/bin.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,9 @@ def pack(self, other: int, size: Optional[int] = None) -> bytes:
:type size: bytes, optional
:rtype: bytes
"""
packed = unhex(f"{other:x}")[::-1]
if size:
packed = packed[:size].ljust(size, b"\x00")
return packed
if size is None:
size = (other.bit_length() + 7) // 8
return other.to_bytes(size, byteorder="little")

def unpack_be(self, other: bytes, size: Optional[int] = None) -> int:
"""
Expand Down Expand Up @@ -123,10 +122,9 @@ def pack_be(self, other: int, size: Optional[int] = None) -> bytes:
:type size: bytes, optional
:rtype: bytes
"""
packed = unhex(f"{other:x}")
if size:
packed = packed[:size].rjust(size, b"\x00")
return packed
if size is None:
size = (other.bit_length() + 7) // 8
return other.to_bytes(size, byteorder="big")

def __call__(self, s, bitsize):
warnings.warn(
Expand Down
7 changes: 7 additions & 0 deletions tests/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@ def test_bigint():
assert bigint.unpack_be(b"ABCDE", 4) == 0x41424344
assert bigint.pack_be(0x41424344, 8) == b"\x00\x00\x00\x00ABCD"

assert bigint.pack(1) == b"\x01"
assert bigint.pack_be(1) == b"\x01"
assert bigint.pack(1234) == b"\xd2\x04"
assert bigint.pack_be(1234) == b"\x04\xd2"
assert bigint.unpack(b"\xd2\x04") == 1234
assert bigint.unpack_be(b"\x04\xd2") == 1234


def test_pack():
assert pack(
Expand Down