notebook1_x509


Notebook 1: X.509 certificates

Jupyter notebook cheat sheet


In [ ]:
# Use Shift+Enter to run the current cell
print 'Hello!'

In [ ]:
# You may also use Alt+Enter to run the current cell, then create a new cell right below
from datetime import datetime
print 'This is the time right now: %s' % datetime.now()

In [ ]:
# If needed, pause the cell edition with Ctrl-M.
# Then you can delete the current cell with D+D. You can also undo cell deletion with Z.
# Finally, should Jupyter become stuck in execution, use Kernel/Interrupt from the menu bar.
print 'Got it!'

Data manipulation with Scapy


In [ ]:
from scapy.all import *

In [ ]:
keystr = open('raw_data/pki/ca_key.der', 'r').read()
print repr(keystr)
# (btw, you can hide the output of a cell by double-clicking on the left of the output)

In [ ]:
privkey = RSAPrivateKey(keystr)
privkey.show()

In [ ]:
v = privkey.version
print 'The \'version\' stripped from any ASN.1 encoding is 0x%02x.' % v.val
print 'The \'version\' field correspond to bytes  %r.' % str(v)

In [ ]:
privkey.version = ASN1_INTEGER(1)
privkey.modulus.val *= 2
privkey.show()

In [ ]:
print 'Original data: %r...' % keystr[:13]
print 'New version bytes:          %r' % str(privkey.version)
print 'New modulus bytes:                      %r...' % str(privkey.modulus)[:6]
print 'Rebuilt data:  %r...' % str(privkey)[:13]

X.509 certificate features


In [ ]:
# Let's reload the original key, then let's load a certificate associated with it
privkey = RSAPrivateKey(keystr)
cert = X509_Cert(open('raw_data/pki/ca_cert.der', 'r').read())
cert.show()

In [ ]:
cert.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.show()
cert.tbsCertificate.subject[-1].rdn[0].show()

In [ ]:
cert.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.modulus == privkey.modulus

In [ ]:
cert.tbsCertificate.extensions[2].show()

In [ ]:
cert.signatureAlgorithm.algorithm

Scapy crypto tools


In [ ]:
# Let's reload the key with Scapy's crypto-enhanced wrapper
privkey = PrivKey('raw_data/pki/ca_key.der')

In [ ]:
privkey.der == keystr

In [ ]:
print privkey.key
print privkey.pubkey

In [ ]:
# We can compute the RSA signature over the part of the certificate which is to be signed
privkey.sign(str(cert.tbsCertificate))

In [ ]:
cert.signatureValue

In [ ]:
# We can quickly modify a certificate field and update the signature accordingly
cert.tbsCertificate.serialNumber.val = 0xdeadcafe
cert.tbsCertificate.subject[-1].rdn[0].value.val = 'my new deadcafe CA'    
cert2 = privkey.resignCert(cert)
cert2.show()