Skip to content

Instantly share code, notes, and snippets.

@neelratanguria
Created March 22, 2022 11:10
Show Gist options
  • Save neelratanguria/f5e86bc4594882760013a2d19acf7e9e to your computer and use it in GitHub Desktop.
Save neelratanguria/f5e86bc4594882760013a2d19acf7e9e to your computer and use it in GitHub Desktop.
Code snippet to convert and decrypt hex output from NRF AES CTR project in python.
from Crypto.Cipher import AES
# Hex prints from debug console from segger
nrf_plain_hex = "45 78 61 6D 70 6C 65 20 73 74 72 69 6E 67 20 74 6F 20 64 65 6D 6F 6E 73 74 72 61 74 65 20 62 61 73 69 63 20 75 73 61 67 65 20 6F 66 20 41 45 53 20 43 54 52 20 6D 6F 64 65 2E"
nrf_cipher = "12 DD C3 EE DF 6E 7E 04 C7 3B DD 0D A3 F5 8E 7E CF 6D A0 A6 76 60 8A 63 01 87 A5 F6 F6 26 B6 86 3A 07 B3 C0 FE D3 E5 3E 94 95 D5 05 EA 62 E7 23 4A F8 9A 20 4C 68 B2 2C D6 E5"
# Initiat vector for aes_ctr project
iv = "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
# Method for converton of of hex string from NRF to bytes in python
def nrf_hex_str_to_bytes(m_hex_str):
split_nrf_plain_hex = x = m_hex_str.split(' ')
split_nrf_plain_hex = "".join(split_nrf_plain_hex)
return bytes.fromhex(split_nrf_plain_hex)
# Convert plain text to bytes
def str_to_byte(plain_key):
return str.encode(plain_key)
# Convert Hex string from segger's debug console to python bytes, verifying decoding in python
pl_text = nrf_hex_str_to_bytes(nrf_plain_hex)
# Print Hex string from segger's debug console to python bytes, verifying decoding in python
print(pl_text)
# Convert cihper hex string from segger's debug console to python bytes object
encrypted_byte = nrf_hex_str_to_bytes(nrf_cipher)
# Convert 16 bytes IV to python bytes object
iv_byte = nrf_hex_str_to_bytes(iv)
# Secret used for encryption in nRF AES CTR project
plain_key = 'NORDIC SEMICONDUCTORAES&MAC TEST'
# Convert secret string to python bytes object
key_byte = str_to_byte(plain_key)
# Create instance of Mode of operation
crypto = AES.new(key_byte, AES.MODE_CTR, counter=lambda: iv_byte)
# Decrypte cipher text
plaintext = crypto.decrypt(encrypted_byte)
# Print cipher text
print(plaintext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment