pythonflaskhttps

Python Flask: Automatically getting or generating SHA-1 fingeriprints


I've created a simple Flask server that runs on HTTPS, accessible by external devices.

When I connect another device (e.g. an ESP8266) I need to provide the SHA-1 fingerprint.

I have no control over the SHA-1 fingerprint that is generated (and I have no idea how it is generated).

So far I've always had to copy and paste the SHA-1 fingerprint from my browser (firefox): I need to visit the server URL through my browser, click on the lock symbol next to the URL, click on "view certificate" and copy and paste the SHA-1 fingerprint.

The SHA-1 fingerprint changes every time I restart the server, so I have to copy and paste it every time (as just described), which is time-consuming.

I was wondering if there was a way to either:

I've done some research on the internet but found nothing so far :(

Thank you in advance!

Here's my code:

from flask import Flask, request

app = Flask(__name__)

@app.route("/", methods=["GET"])
def hello():
    return "Hello World!

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080, ssl_context='adhoc')

Solution

  • import ssl, hashlib
    
    cert = ssl.get_server_certificate(('my_server_url', my_server_port))
    
    pem_cert = ssl.PEM_cert_to_DER_cert(cert)
    sha1_fingerprint = hashlib.sha1(pem_cert).hexdigest()
    print(sha1_fingerprint)
    

    Thank you so much!