Duplicate 'openssl rsautl' verification in Python

776 views Asked by At

I do this in bash:

head -c 128 <signed_fw_image> > <image_sign>

openssl rsautl -verify -inkey <public_rsa_key> -in <image_sign> -pubin > <out_sign_result>
md5sum <raw_image_bin> | xxd -r -p > <out_orig_result>
diff <out_sign_result> <out_orig_result>

How I can implement this in python and which libraries should I use?

1

There are 1 answers

0
Jesko Hüttenhain On

I had a similar problem recently and I came by here on my way to eventually read the rsautl source code. It does just a single raw RSA round. The following Python 3 script can be used to reproduce the behavior of rsautl -verify and relies on the pycryptodome package, which I recommend for this task:

# emulates the command: openssl rsautl -verify -pubin -inkey $1

import sys
import re
from Crypto.PublicKey import RSA

with open(sys.argv[1], 'rb') as keyfile:
    key = RSA.import_key(keyfile.read())

msg = sys.stdin.buffer.read()
assert len(msg) <= key.size_in_bytes(), 'block too large.'

msg = int.from_bytes(msg, byteorder='big')

# RSA happens here:
dec = pow(msg, key.e, key.n)

dec = dec.to_bytes(key.size_in_bytes(), byteorder='big')
dec = re.match(BR'^\x00\x01\xFF+\x00(.*)$', dec, flags=re.DOTALL)
assert dec, 'output format invalid'

sys.stdout.buffer.write(dec.group(1))

I assume that this was the tricky part, you can compute the MD5 checksum of your file by using the builtin hashlib module.