import hashlib import sys from intelhex import IntelHex from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding, rsa from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization import os import binascii # Path to the hex file you want to load file_path = 'W:/xxx/xxx/xxx_input.hex' privkey_path = 'W:/xxx/xxx/rivate_1024key.pem' pubkey_path = 'W:/xxx/xxx/public_1024key.pem' output_file = 'W:/xxx/xxx//Hash.txt' outhex_file = 'W:/xxx/xxx/xxx_output.hex' # Define the ranges() function def ranges(addresses): start = addresses[0] end = addresses[0] for address in addresses[1:]: if address == end + 1: end = address else: yield start, end start = address end = address yield start, end # Load the Intel Hex file hex = IntelHex(file_path) # Get the sorted list of addresses addresses = hex.addresses() addresses.sort() # Iterate over address ranges and extract the data data_list = list(ranges(addresses)) for start, end in data_list: size = end - start + 1 data = list(hex.tobinarray(start=start, size=size)) # Convert the data to hexadecimal format hex_data = ''.join(format(byte, '02x') for byte in data) data_bytes = bytes.fromhex(hex_data) hasher = hashlib.sha256() hasher.update(data_bytes) hash_value = hasher.hexdigest() # Print the hash value in hexadecimal format print("SHA256 Hash Value:", hash_value) # Load the private key from file try: with open(privkey_path, 'rb') as f: private_key = serialization.load_pem_private_key( f.read(), password=None, backend=default_backend() ) print("private_key:", private_key) # If no exception occurred, the private key was loaded successfully print("Private key loaded successfully.") # Use the private key for signing or other operations except Exception as e: print("Error loading private key:", e) # Digest to be signed # Convert the hash value to bytes digest_bytes = bytes.fromhex(hash_value) # Save the digest bytes to a file with open(output_file, 'wb') as file: file.write(digest_bytes) print("Digest:", digest_bytes) # Sign the digest with the private key signature = private_key.sign( digest_bytes, padding.PKCS1v15(), # Use PKCS1v15 padding scheme for RSA signatures hashes.SHA256() # Use SHA256 hashing algorithm ) # Convert the signature to hexadecimal format if needed hex_signature = signature.hex() # Print the hexadecimal signature print("Hexadecimal signature:", hex_signature)