From ea5abfe149c8c86f721ac5a300cab3eaefe5a9d1 Mon Sep 17 00:00:00 2001 From: Mitja HORVAT Date: Wed, 3 Nov 2021 11:26:02 +0100 Subject: [PATCH] python: Implement phogen encode Implement phogen.encode() to encode Bhashes to phogen strings. This commit also adds unit tests for the above function. --- python/passgeny/phogen.py | 19 +++++++++++++++++++ tests/meson.build | 9 ++++++--- tests/test_phogen.py | 27 +++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 3 deletions(-) create mode 100755 tests/test_phogen.py diff --git a/python/passgeny/phogen.py b/python/passgeny/phogen.py index e69de29..bfe9779 100644 --- a/python/passgeny/phogen.py +++ b/python/passgeny/phogen.py @@ -0,0 +1,19 @@ +from passgeny import bhash, phogen_map + +def encode(bh: bhash.Bhash, ph_len: int): + """ + Consume the Bhash and return a string of length ph_len + + This function generates a phonetic representation of the binary data in + Bhash. + """ + phogen = '' + ngram = ' ' + for x in range(ph_len): + ngram_space = phogen_map.g_phonetic_map[ngram] + n = bh.modulo(len(ngram_space)) + letter = ngram_space[n] + ngram = ngram[1:] + letter + phogen += letter + + return phogen diff --git a/tests/meson.build b/tests/meson.build index 499db8c..8cedcec 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -9,8 +9,11 @@ test('test_phogen_map', 'PHOGEN_MAP_PY=@0@'.format(_phogen_map_py), 'PHOGEN_WORD_LIST=@0@'.format(_word_list)]) -test('test_bhash', +test('test_bhash_py', find_program('test_bhash.py'), - env: ['SOURCE_ROOT=' + meson.project_source_root(), - 'PYTHONPATH=' + PYTHONPATH]) + env: ['PYTHONPATH=' + PYTHONPATH]) + +test('test_phogen_py', + find_program('test_phogen.py'), + env: ['PYTHONPATH=' + PYTHONPATH]) diff --git a/tests/test_phogen.py b/tests/test_phogen.py new file mode 100755 index 0000000..35024f5 --- /dev/null +++ b/tests/test_phogen.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +import hashlib + +from passgeny import phogen +from passgeny import bhash + +PHO_GEN_TEST = [ + [ b"passgeny", "herang xiasem zitend qibele" ], + [ b"phonetic", "lineum foneum zybale mangur" ], + [ b"generator", "latole elitab ackina exprou" ], + [ b"password", "nulize nomere fonici crednt" ], + [ b"duck", "catabb rompor cricin prunsi" ] ] + +for pt in PHO_GEN_TEST: + bh = bhash.Bhash() + bh.from_bytes(hashlib.sha256(pt[0]).digest()) + wa = [] + + for x in range(4): + wa.append(phogen.encode(bh, 6)) + + word = " ".join(wa) + + if word != pt[1]: + raise Exception("Test failed: {} != {}".format(word, pt1)) + + print(word)