Skip to content

Instantly share code, notes, and snippets.

@carlopires
Created September 1, 2015 18:29
Show Gist options
  • Save carlopires/de085999dc69a13efe60 to your computer and use it in GitHub Desktop.
Save carlopires/de085999dc69a13efe60 to your computer and use it in GitHub Desktop.
"""
@author: Carlo Pires <carlopires@gmail.com>
To generate the certificate with openssl:
openssl genrsa 2048 > o365app.key
openssl req -new -x509 -nodes -sha512 -days 365 -key o365app.key > o365app.crt
To generate key credentials for MS Azure:
python gen_key_credentials.py o365app.crt
"""
import sys
import ssl
import uuid
import json
import binascii
import hashlib
def gen_key_credentials_from_crt(filename):
with open(filename, 'r') as cert:
crt = cert.read()
cert_raw = ssl.PEM_cert_to_DER_cert(crt)
cert_b64 = binascii.b2a_base64(cert_raw)[:-1]
cert_hash = hashlib.sha1(cert_raw).digest()
cert_hash_b64 = binascii.b2a_base64(cert_hash)[:-1]
cert_id = str(uuid.uuid4())
key_credentials = {
'keyCredentials': [{
'customKeyIdentifier': cert_hash_b64.decode(),
'keyId': cert_id,
'type': 'AsymmetricX509Cert',
'usage': 'Verify',
'value': cert_b64.decode(),
}]
}
return json.dumps(key_credentials, indent=2)
if __name__ == '__main__':
if len(sys.argv) != 2:
print('Use: {} <certificate_file.pem>')
else:
print(gen_key_credentials_from_crt(sys.argv[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment