Last active
August 29, 2017 08:10
-
-
Save llopv/f967b8cb74c5b3080f63de2114e6385d to your computer and use it in GitHub Desktop.
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
(function() { | |
let alg = {name: "AES-GCM", length: 256} | |
let keyUsages = ["encrypt", "decrypt"] | |
function base64ToBuffer(base64) { | |
let binary_string = window.atob(base64) | |
let len = binary_string.length | |
let bytes = new Uint8Array(len) | |
for (var i = 0; i < len; i++) { | |
bytes[i] = binary_string.charCodeAt(i) | |
} | |
return bytes.buffer | |
} | |
let getCryptoKey = (key) => { | |
let keydata = { | |
kty: "oct", | |
k: key, | |
alg: "A256GCM", | |
ext: true, | |
}; | |
return window.crypto.subtle.importKey("jwk", keydata, alg, false, keyUsages) | |
} | |
let decrypt = (key, msg) => { | |
msg = msg.split(";") | |
let iv = base64ToBuffer(msg[0]) | |
let data = base64ToBuffer(msg[1]) | |
let additionalData = base64ToBuffer(msg[2]) | |
let params = { | |
name: "AES-GCM", | |
iv, | |
additionalData, | |
} | |
return window.crypto.subtle.decrypt(params, key, data).then(buffer => { | |
return new TextDecoder("utf8").decode(buffer) | |
}) | |
} | |
let onServerResponse = (json) => { | |
console.log(json) | |
let texts = {} | |
getCryptoKey(key).then(k => { | |
key = k; | |
let snapshot = json.snapshots[Object.keys(json.snapshots)[0]] | |
Promise.all(Object.keys(snapshot.ciphertexts).map((c) => { | |
return decrypt(key, snapshot.ciphertexts[c]).then(t => texts[c] = t) | |
})).then(() => { | |
console.log(texts) | |
let content = "" | |
let pieces = snapshot.pieces | |
console.log(pieces) | |
for (let k of Object.keys(pieces)) { | |
console.log(JSON.stringify(pieces[k])) | |
console.log(texts[pieces[k].opId].substring(pieces[k].offset, pieces[k].offset+pieces[k].len)) | |
content += texts[pieces[k].opId].substring(pieces[k].offset, pieces[k].offset+pieces[k].len) | |
} | |
let i = 0 | |
document.querySelector('.document').innerHTML = document.querySelector('.document').innerHTML.split('').map(c => { | |
if (c == '*') { | |
return content.charAt(i++) | |
} else { | |
return c | |
} | |
}).join('') | |
}) | |
}) | |
} | |
let waveId = location.hash.substr(1).split('!')[0] | |
let key = location.hash.substr(1).split('!')[1]; | |
let r = new XMLHttpRequest() | |
r.open("GET", "/crypto/snapshot/" + waveId + "/local.net/conv+root", true) | |
r.onreadystatechange = function () { | |
if (r.readyState != 4 || r.status != 200) return | |
onServerResponse(JSON.parse(r.responseText)) | |
} | |
r.send() | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment