Skip to content

Commit

Permalink
Merge pull request openwallet-foundation#78 from Indicio-tech/feature…
Browse files Browse the repository at this point in the history
…/hashlink-verification

feat: Add hashlink verification code
  • Loading branch information
dbluhm authored Sep 2, 2022
2 parents f647b5e + 6878cef commit 09d0538
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
43 changes: 42 additions & 1 deletion aries_cloudagent/protocols/issue_credential/v2_0/hashlink.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,50 @@ def _deserialize_metadata(cls, metadata: str) -> Dict[str, Any]:

return deserialized

@classmethod
def _deserialize_data(cls, data: bytes) -> bytes:
"""
Deserialize the data portion of a hashlink.
Parameters:
data -> The data portion of the hashlink
Returns:
bytes -> The decoded hash of the hashlink data
"""
raw = multibase.decode(data)
header = raw[:2]
raw_hash = raw[2:]

# Currently only SHA2-256 is supported
if header[0] != 0x12:
raise Exception("Unknown hash algorithm used: {}".format(header[0]))

length = header[1]
if length != len(raw_hash):
raise Exception("hash length doesn't match length header")

return raw_hash

@classmethod
def verify(
cls, link: str, data: Optional[bytes] = None, *, check_remote: bool = False
) -> bool:
"""Verify the hash of the data linked to by the hashlink."""
...

link_split = link.split(cls.SEPARATOR)

if link_split[0] != cls.SCHEME:
return False

link_data_hash = cls._deserialize_data(link_split[1])

# TODO add check for when check_remote is true
if not check_remote:
if data is None:
data = b""
data_hash = sha256(data).digest()

if link_data_hash == data_hash:
return True

return False
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

EXAMPLE_DATA = b"Hello World!"
EXAMPLE_LINK = "hl:zQmWvQxTqbG2Z9HPJgG57jjwR154cKhbtJenbyYTWkjgF3e:zuh8iaLobXC8g9tfma1CSTtYBakXeSTkHrYA5hmD4F7dCLw8XYwZ1GWyJ3zwF"
EXAMPLE_DATA_SHA = bytes.fromhex("7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069")


def test_example_link():
Expand All @@ -23,3 +24,15 @@ def test_serialize_metadata():
)

assert hashlink._serialize_metadata() == EXAMPLE_LINK.split(":")[2]

def test_deserialize_data():

data = EXAMPLE_LINK.split(":")[1]

assert Hashlink._deserialize_data(data) == EXAMPLE_DATA_SHA

def test_verify_link():

assert Hashlink.verify(EXAMPLE_LINK, EXAMPLE_DATA)
assert Hashlink.verify(EXAMPLE_LINK, b"Bad Data!") == False
assert Hashlink.verify(EXAMPLE_LINK) == False

0 comments on commit 09d0538

Please sign in to comment.