Created
January 15, 2016 11:13
-
-
Save tgermain/8b11936c9edd6e4f067b to your computer and use it in GitHub Desktop.
mimic docker/libtrust keyIDFromCryptoKey, usefull when using JWT as authentication for a docker registry v2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
This code mimic the behaviour of docker/libtrust function keyIDFromCryptoKey | |
It is usefull when using Json Web Token as authentication in a docker regsitry V2. | |
source : https://github.com/docker/libtrust/blob/9cbd2a1374f46905c68a4eb3694a130610adc62a/util.go#L194 | |
""" | |
from cryptography import x509 | |
from cryptography.hazmat.backends import default_backend | |
from cryptography.hazmat.primitives import serialization | |
from cryptography.hazmat.primitives import hashes | |
import base64 | |
def key_id_from_cert_file(cert_filepath): | |
with open(cert_filepath, "rb") as f: | |
raw_cert = f.read() | |
cert = x509.load_pem_x509_certificate(raw_cert, default_backend()) | |
pub_key = cert.public_key() | |
return key_id_from_public_key(pub_key) | |
def key_id_from_public_key(public_key): | |
""" | |
Generate and return a 'libtrust' fingerprint of the public key. | |
""" | |
# encode the key as DER encoded ASN1 | |
der = public_key.public_bytes( | |
encoding=serialization.Encoding.DER, | |
format=serialization.PublicFormat.SubjectPublicKeyInfo | |
) | |
# compute SHA256 digest | |
digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) | |
digest.update(der) | |
pub_hash = digest.finalize() | |
digest_hash = base64.b32encode(pub_hash) | |
# format the digest as 12 base32 groups like so : | |
# ABCD:EFGH:IJKL:MNOP:QRST:UVWX:YZ23:4567:ABCD:EFGH:IJKL:MNOP | |
res = [] | |
for idx in range(len(digest_hash))[::4]: | |
res.append(digest_hash[idx:idx+4]) | |
return ":".join(res[:12]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment