Skip to content

Commit

Permalink
made decrypt exception more specific
Browse files Browse the repository at this point in the history
  • Loading branch information
monty committed Jun 5, 2024
1 parent 3d07764 commit 5a437fb
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
6 changes: 3 additions & 3 deletions my_scratch.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ async def get_key() -> str:
return input('keystore key: ')

my_enc = KeyDataEncrypter(get_key=get_key)
new_store = FileKeyStore(new_file,
encrypter=my_enc)
new_store = SQLiteKeyStore(new_file,
encrypter=None)

await new_store.convert_memstore(old_file)

Expand Down Expand Up @@ -50,7 +50,7 @@ async def get_key() -> str:
# from monstr.encrypt import Keys
# await new_store.update(Keys(), 'monty_test')

asyncio.run(test_store())
asyncio.run(convert_store())



Expand Down
13 changes: 8 additions & 5 deletions src/monstr/encrypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,9 @@ def decrypt_event(self, evt: Event) -> Event:
return ret


class DecryptionException(Exception):
pass

class NIP4Encrypt(Encrypter):

def __init__(self, key: Keys | str):
Expand Down Expand Up @@ -434,13 +437,13 @@ def _decode_payload(payload) -> tuple[bytes, bytes, bytes]:

# TODO: size limits should be being calculated from MIN/MAX PAD
if p_size < 132 or p_size > 87472:
raise Exception(f'invalid payload size {p_size}')
raise DecryptionException(f'invalid payload size {p_size}')

data = base64.b64decode(payload)
d_size = len(data)

if d_size < 99 or d_size > 65603:
raise Exception(f'invalid payload size {p_size}')
raise DecryptionException(f'invalid payload size {p_size}')

version = data[0]
nonce = data[1:33]
Expand All @@ -449,7 +452,7 @@ def _decode_payload(payload) -> tuple[bytes, bytes, bytes]:

# only current/supported version
if version != 2:
raise ValueError(f'nip44_encrypt unsupported version {version}')
raise DecryptionException(f'nip44_encrypt unsupported version {version}')

return nonce, cipher_text, mac

Expand All @@ -467,7 +470,7 @@ def _get_conversation_key(self, for_pub_k: str) -> bytes:
def _get_message_key(conversion_key: bytes, nonce: bytes) -> tuple[bytes, bytes, bytes]:

if len(nonce) != 32:
raise ValueError('NIP44Encrypt:: _get_message_key nonce is not 32 bytes long')
raise DecryptionException('NIP44Encrypt:: _get_message_key nonce is not 32 bytes long')

msg_key = NIP44Encrypt._hkdf_expand(prk=conversion_key,
info=nonce,
Expand Down Expand Up @@ -536,7 +539,7 @@ def decrypt(self, payload: str, for_pub_k: str) -> str:
hash_function=NIP44Encrypt.V2_HASH)

if calculated_mac != mac:
raise ValueError('invalid MAC')
raise DecryptionException('invalid MAC')

padded = NIP44Encrypt._do_decrypt(ciper_text=ciper_text,
key=chacha_key,
Expand Down

0 comments on commit 5a437fb

Please sign in to comment.