Python Forum

Full Version: [cryptography.io] How to convert DER signature to ECDSA
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello all,

According to cryptography.io documentation the signature for
cryptography.hazmat.primitives.asymmetric.ec.ECDSA
is a bytes object, whose contents is DER encoded
and can be decoded using decode_dss_signature()

and decode_dss_signature is returning decoded tuple (r,s)

r, s = decode_dss_signature(signature)
How to properly concatenate (r,s) to binary again.

Found something like
r_bytes = r.to_bytes((r.bit_length() + 7) // 8, 'big')
s_bytes = s.to_bytes((s.bit_length() + 7) // 8, 'big')
Is this correct? and if so what's next?
In the end I went for openssl with subprocess

from codecs import getdecoder
from re import findall
from subprocess import Popen, PIPE

with open('app.dat', 'rb') as dat_file:
    signable_content = dat_file.read()
    out = Popen([
        'openssl',
        'dgst',
        '-sha256',
        '-binary',
        '-sign', 'private-key.pem',
    ], stdout=PIPE, stderr=PIPE, stdin=PIPE)
    signature_output, err = out.communicate(input=signable_content)
    # Extract raw data from ASN.1 DER signature
    out = Popen([
        'openssl',
        'asn1parse',
        '-inform',
        'DER',
    ], stdout=PIPE, stderr=PIPE, stdin=PIPE)
    formatted_signature, err = out.communicate(input=signature_output)
    formatted_signature = formatted_signature.decode('utf-8')
    # Extract only R and S values
    regex = r'\b[0-9A-F]{64}\b'
    rs_values = findall(regex, formatted_signature)
    # Concatenate R and S values
    rs_values = ''.join(str(v) for v in rs_values)
    decode_hex = getdecoder('hex_codec')
    signature = decode_hex(rs_values)[0]