Skip to content

Instantly share code, notes, and snippets.

@iffy
Created June 3, 2016 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iffy/f5a88ad1e7eb064417be4bfea512b941 to your computer and use it in GitHub Desktop.
Save iffy/f5a88ad1e7eb064417be4bfea512b941 to your computer and use it in GitHub Desktop.
The interface I'm hoping for when I do cryptographic stuff

Cryptography for Humans

Create a private key:

>>> from humancrypto import PrivateKey
>>> key = PrivateKey()
>>> with open('private.key', 'wb') as fh:
...     fh.write(key.serialize())

Load a private key from a file (these are all equivalent). There are equivalent methods for CSRs, Certs, Public Keys:

>>> key = PrivateKey.load(filename='private.key')
>>> key = PrivateKey.load(open('private.key', 'rb'))
>>> key = PrivateKey.load(open('private.key', 'rb').read())

Create a Certificate Signing Request (CSR):

>>> from humancrypto import CSR
>>> csr = CSR(key.public_key, common_name=u'bob', ca=True)
>>> csr.attribs['common_name']
u'bob'
>>> with open('ca.csr', 'wb') as fh:
...     fh.write(csr.serialize())

Sign a CSR:

>>> cert = key.sign_csr(csr)
>>> cert.attribs['common_name']
u'bob'
>>> with open('ca.cert', 'wb') as fh:
...     fh.write(cert.serialize())

Verify that a certificate was signed by a private key:

>>> key.verify(cert)

Encrypt some data:

>>> ciphertext = key.public_key.encrypt('something')

Decrypt it:

>>> key.decrypt(ciphertext)
'something'

Verify a certificate with a CA certificate:

>>> ca_cert.verify(presented_cert)
>>> presented_cert.attribs['common_name']
'foo'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment