Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Generate SHA256 fingerprint from a public key
# coding=utf-8
# Displays SHA256 fingerprint of public key in Python 2/3.
# Modified by Steven Maude from
# MIT licence.
# Usage: obtain a public key using ssh-keyscan <host> >
# then `cut -f3 -d " "`
import base64
import binascii
import hashlib
import re
import sys
def sha256_fingerprint_from_pub_key(data):
data = data.strip()
# accept either base64 encoded data or full pub key file,
# same as `fingerprint_from_ssh_pub_key
if ('^ssh-(?:rsa|dss) ', data)):
data = data.split(None, 2)[1]
# Python 2/3 hack. May be a better solution but this works.
data = bytes(data, 'ascii')
except TypeError:
data = bytes(data)
digest = hashlib.sha256(binascii.a2b_base64(data)).digest()
encoded = base64.b64encode(digest).rstrip(b'=') # ssh-keygen strips this
return "SHA256:" + encoded.decode('utf-8')
def main():
if __name__ == '__main__':

This comment has been minimized.

Copy link

@unphased unphased commented Nov 30, 2020

I found that all you need to do for getting the sha256 fingerprint shown in github (to check it against your local key) is:

ssh-keygen -E sha256 -l -f ~/.ssh/<key>.pub

This script did not work for me, it reports some binascii error.


This comment has been minimized.

Copy link
Owner Author

@StevenMaude StevenMaude commented Dec 3, 2020

I just tested the script. It still works for me.

The primary use was for getting fingerprints from servers. The cut gets the base64 part of the file. You may need to cut a different field to get the correct part for this script, if using on a key which doesn't have a server name, for example.

I put this here, I think, at a time when the OS I was using did not show SHA256 fingerprints directly. This was probably because OpenSSH hadn't yet been updated.

The ssh-keygen command works fine too 🙂


This comment has been minimized.

Copy link

@unphased unphased commented Dec 3, 2020

Could well be that my key i tried with is a rather than a more typical rsa.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.