Skip to content

Commit

Permalink
πŸ—“ Sep 3, 2023 11:47:14 PM
Browse files Browse the repository at this point in the history
✨ to/from messagepack
✨ bifid en/decode
✨ helper functions
βž• deps added/updated
πŸ§ͺ tests added/updated
  • Loading branch information
securisec committed Sep 4, 2023
1 parent e5f88fd commit 8234ce7
Show file tree
Hide file tree
Showing 10 changed files with 179 additions and 6 deletions.
4 changes: 3 additions & 1 deletion TODO
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ New ideas:
☐ ✨ whitespace encoding https://www.dcode.fr/whitespace-language
☐ ✨ huffman encode/decode
☐ ✨ new plugin that can help detect encoding type trained on random data
☐ ✨ upside down writing

Bug:

Expand Down Expand Up @@ -63,6 +62,9 @@ Misc:
☐ cyberchef recipe to chepy recipe converter

Archive:
βœ” ✨ bifd
βœ” ✨ to/from messagepack
βœ” ✨ upside down writing
βœ” ✨ bacon encode/decode
βœ” rsa enc/dec with key or from pem directly
βœ” ✨ to/from pickle
Expand Down
2 changes: 1 addition & 1 deletion chepy/chepy_plugins
21 changes: 21 additions & 0 deletions chepy/modules/dataformat.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from urllib.parse import unquote_plus as _urllib_unquote_plus

crypto_number = lazy_import.lazy_module("Crypto.Util.number")
msgpack = lazy_import.lazy_module("msgpack")

from ..core import ChepyCore, ChepyDecorators
from chepy.modules.internal.constants import Encoding
Expand Down Expand Up @@ -1780,3 +1781,23 @@ def from_upside_down(self, reverse: bool = False):
else:
self.state = hold
return self

@ChepyDecorators.call_stack
def to_messagepack(self) -> DataFormatT:
"""To MessagePack
Returns:
Chepy: The Chepy object.
"""
self.state = msgpack.packb(self.state)
return self

@ChepyDecorators.call_stack
def from_messagepack(self) -> DataFormatT:
"""From MessagePack
Returns:
Chepy: The Chepy object.
"""
self.state = msgpack.unpackb(self.state, raw=False)
return self
2 changes: 2 additions & 0 deletions chepy/modules/dataformat.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,5 @@ class DataFormat(ChepyCore):
def from_bacon(self: DataFormatT, A: Literal['A', '0']=..., B: Literal['B', '1']=..., complete: bool=..., split_by: bytes=..., invert: bool=...) -> DataFormatT: ...
def to_upside_down(self: DataFormatT, reverse: bool=False) -> DataFormatT: ...
def from_upside_down(self: DataFormatT, reverse: bool=False) -> DataFormatT: ...
def to_messagepack(self: DataFormatT) -> DataFormatT: ...
def from_messagepack(self: DataFormatT) -> DataFormatT: ...
121 changes: 120 additions & 1 deletion chepy/modules/encryptionencoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
decrypt_pad as _ls47_dec,
derive_key as _derive_key,
)
from .internal.constants import Ciphers

import lazy_import

Expand Down Expand Up @@ -1215,7 +1216,7 @@ def to_morse_code(
morse_code_dict[k] = v.replace(".", dot).replace("-", dash)
for word in self._convert_to_str().split():
for w in word:
encode += morse_code_dict.get(w.upper(), '') + letter_delim
encode += morse_code_dict.get(w.upper(), "") + letter_delim
encode += word_delim
self.state = encode
return self
Expand Down Expand Up @@ -1553,3 +1554,121 @@ def ls47_decrypt(self, password: str, padding: int = 10) -> EncryptionEncodingT:
key = _derive_key(password)
self.state = _ls47_dec(key, padding, self._convert_to_str())
return self

@ChepyDecorators.call_stack
def bifid_encode(self, key: Union[bytes, str] = "") -> EncryptionEncodingT:
"""Bifid / polybius decode
Args:
key (Union[str, bytes], optional): Key. Defaults to "".
Returns:
Chepy: The Chepy object.
"""
key = self._bytes_to_str(key)
key = "".join(re.findall(r"[A-Z]+", key))
keyword_str = key.upper().replace("J", "I")
keyword_set = set(keyword_str)
keyword_list = []
alpha = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
x_co = []
y_co = []
structure = []

output = ""
count = 0

polybius = Ciphers.gen_polybius_square(keyword_str)

for letter in self._convert_to_str().replace("J", "I"):
alp_ind = letter.upper() in alpha
pol_ind = -1

if alp_ind:
for i in range(5):
if letter.upper() in polybius[i]:
pol_ind = polybius[i].index(letter.upper())
x_co.append(pol_ind)
y_co.append(i)

if letter in alpha:
structure.append(True) # pragma: no cover
elif alp_ind:
structure.append(False)
else:
structure.append(letter) # pragma: no cover

trans = "".join(map(str, y_co)) + "".join(map(str, x_co))

for pos in structure:
if isinstance(pos, bool):
coords = trans[2 * count : 2 * count + 2]
coords = list(map(int, coords))

output += (
polybius[coords[0]][coords[1]]
if pos
else polybius[coords[0]][coords[1]].lower()
)
count += 1
else:
output += pos # pragma: no cover

self.state = output
return self

@ChepyDecorators.call_stack
def bifid_decode(self, key: Union[str, bytes] = ""):
"""Bifid / polybius decode
Args:
key (Union[str, bytes], optional): Key. Defaults to "".
Returns:
Chepy: The Chepy object.
"""
key = self._bytes_to_str(key)
key = "".join(re.findall(r"[A-Z]+", key))
keyword_str = key.upper().replace("J", "I")
keyword_set = set(keyword_str)
alpha = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
structure = []

output = ""
count = 0
trans = ""

polybius = Ciphers.gen_polybius_square(keyword_str)

for letter in self._convert_to_str().replace("J", "I"):
alp_ind = letter.upper() in alpha
pol_ind = -1

if alp_ind:
for i in range(5):
if letter.upper() in polybius[i]:
pol_ind = polybius[i].index(letter.upper())
trans += f"{i}{pol_ind}"

if letter in alpha:
structure.append(True) # pragma: no cover
elif alp_ind:
structure.append(False)
else:
structure.append(letter) # pragma: no cover

for pos in structure:
if isinstance(pos, bool):
coords = [int(trans[count]), int(trans[count + len(trans) // 2])]

output += (
polybius[coords[0]][coords[1]]
if pos
else polybius[coords[0]][coords[1]].lower()
)
count += 1
else:
output += pos # pragma: no cover

self.state = output
return self
2 changes: 2 additions & 0 deletions chepy/modules/encryptionencoding.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,5 @@ class EncryptionEncoding(ChepyCore):
def from_letter_number_code(self: EncryptionEncodingT, delimiter: Union[str, bytes]=..., join_by: Union[str, bytes]=...) -> EncryptionEncodingT: ...
def ls47_encrypt(self: EncryptionEncodingT, password: str, padding: int=..., signature: str=...) -> EncryptionEncodingT: ...
def ls47_decrypt(self: EncryptionEncodingT, password: str, padding: int=...) -> EncryptionEncodingT: ...
def bifid_encode(self: EncryptionEncodingT, key: Union[bytes, str]='') -> EncryptionEncodingT: ...
def bifid_decode(self: EncryptionEncodingT, key: Union[bytes, str]='') -> EncryptionEncodingT: ...
14 changes: 14 additions & 0 deletions chepy/modules/internal/constants.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
class Ciphers:
@staticmethod
def gen_polybius_square(keyword):
alpha = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
pol_array = list(keyword.upper() + alpha)
pol_array = sorted(list(set(pol_array)), key=lambda x: (pol_array.index(x) // 5, pol_array.index(x) % 5))
polybius = []

for i in range(5):
polybius.append(pol_array[i * 5:i * 5 + 5])

return polybius


class Encoding(object):
UPSIDE_DOWN = {
"!": "Β‘",
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@ regex
typing_extensions
pretty-errors==1.2.25
lz4==4.3.2
passlib==1.7.4
passlib==1.7.4
msgpack==1.0.4
12 changes: 10 additions & 2 deletions tests/test_dataformat.py
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,14 @@ def test_bacon():
assert Chepy(out).from_bacon().o == b"HELLO"
assert Chepy("hello").to_bacon(A="0", B="1").from_bacon(A="0", B="1").o == b"HELLO"


def test_upside_down():
assert Chepy('hello').to_upside_down().from_upside_down().o == b'hello'
assert Chepy('hello').to_upside_down(True).from_upside_down(True).o == b'hello'
assert Chepy("hello").to_upside_down().from_upside_down().o == b"hello"
assert Chepy("hello").to_upside_down(True).from_upside_down(True).o == b"hello"


def test_messagepack():
assert Chepy("hello").to_messagepack().from_messagepack().o == b"hello"
assert Chepy("hello").to_messagepack().from_messagepack().o == b"hello"
assert Chepy(["hello"]).to_messagepack().from_messagepack().o == ["hello"]
assert Chepy({"a": "hello"}).to_messagepack().from_messagepack().o == {"a": "hello"}
4 changes: 4 additions & 0 deletions tests/test_encryptionencoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -782,3 +782,7 @@ def test_ls47_enc_dec():
Chepy("hello").ls47_encrypt("password").ls47_decrypt("password").o
== b"hello---"
)


def test_bifid():
assert Chepy("hello").bifid_encode("!H").bifid_decode("!H").o == b"hello"

0 comments on commit 8234ce7

Please sign in to comment.