Embedding JavaScript in a Jupyter notebook#
I recently found out modern browsers include a JavaScript API for creating public/private keys for cryptography.
I used this as an opportunity to figure out how to run JavaScript in a Jupyter notebook cell, using the IPython.display.Javascript mechanism.
This mechanism allows you to execute JavaScript that will be used to render a cell. It includes a copy of jQuery and makes a element
variable available corresponding to the cell your code is running in. It also provides a IPython.notebook.kernel.execute()
method which can be used to execute Python code from JavaScript.
Here’s what I came up with:
1from IPython.display import Javascript, display2
3display(Javascript("""4function generateKey() {5 window.crypto.subtle6 .generateKey(7 {8 name: "RSA-OAEP",9 modulusLength: 4096,10 publicExponent: new Uint8Array([1, 0, 1]),11 hash: "SHA-256",12 },13 true,14 ["encrypt", "decrypt"]15 )16 .then((keyPair) => {17 crypto.subtle.exportKey("jwk", keyPair.privateKey).then((v) => {18 element.find("textarea:first").val(JSON.stringify(v, null, 4));19 IPython.notebook.kernel.execute(20 "private_key = " + JSON.stringify(JSON.stringify(v, null, 4))21 );22 });23 crypto.subtle.exportKey("jwk", keyPair.publicKey).then((v) => {24 element.find("textarea:last").val(JSON.stringify(v, null, 4));25 IPython.notebook.kernel.execute(26 "public_key = " + JSON.stringify(JSON.stringify(v, null, 4))27 );28 });29 });30}31element.append(`32<h2>Generate a public/private key in JavaScript</h2>33<p><button>Generate key</button></p>34<h3>Private key</h3>35<textarea style="width: 100%; height: 20em"></textarea>36<h3>Public key</h3>37<textarea style="width: 100%; height: 20em"></textarea>38`);39element.find("button").click(generateKey);40"""))
This works! I get a new cell in the document containing the HTML from that backtick string at the end of the JavaScript code. When I click the button it runs my generateKey
function which generates a new key, displays it in the two textareas and makes that key available to the Jupyter environment as the public_key
and private_key
variables. I can then use them in subsequent cells from Python like this:
1import json2private = json.loads(private_key)3public = json.loads(public_key)