Skip to content

Instantly share code, notes, and snippets.

@davidp94
Created May 22, 2021 09:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidp94/12fa68490f5edfca278be8491728c391 to your computer and use it in GitHub Desktop.
Save davidp94/12fa68490f5edfca278be8491728c391 to your computer and use it in GitHub Desktop.
python account identifier from Principal Id
import hashlib
import base64
import math
import binascii
if __name__ == '__main__':
principal_id_str = "m7b5y-itxyr-mr2gt-kvadr-2dity-bh3n5-ff7bb-vvm2v-3ftew-5wjtg-2qe"
subaccount = bytearray(32)
# principal_id_str = "kb4lg-bqaaa-aaaab-qabfq-cai"
# principal_id_str = "gmk2m-oiaaa-aaaab-qaaja-cai"
principal_id_str = principal_id_str.replace('-', '')
pad_length = math.ceil(len(principal_id_str) / 8) * 8 - len(principal_id_str)
print(principal_id_str)
principal_bytes = base64.b32decode(principal_id_str.encode('ascii') + b'=' * pad_length, True, None)
principal_bytes = principal_bytes[4:] # remove CRC32 checksum bytes
ADS = b"\x0Aaccount-id"
h = hashlib.sha224()
h.update(ADS)
h.update(principal_bytes)
print(subaccount)
h.update(subaccount)
checksum = binascii.crc32(h.digest())
checksum_bytes = checksum.to_bytes(4, byteorder='big')
identifier = checksum_bytes + h.digest()
print(identifier)
print('identifier {}'.format(identifier.hex()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment