diff options
author | Marvin Borner | 2019-01-24 21:55:46 +0100 |
---|---|---|
committer | Marvin Borner | 2019-01-24 21:55:46 +0100 |
commit | baf6695a812ab78aadf315986970e9aa3de7c712 (patch) | |
tree | 9738bf180015feb92081aff8f1d6a81244c8ebf4 /public | |
parent | 2abf58c832112e6ef950bbd6a7616eac22ac4b10 (diff) |
Overworked encrypting (only works on first load)
Diffstat (limited to 'public')
-rw-r--r-- | public/scripts/2_encryption.js | 79 | ||||
-rw-r--r-- | public/scripts/chat.js | 31 |
2 files changed, 60 insertions, 50 deletions
diff --git a/public/scripts/2_encryption.js b/public/scripts/2_encryption.js index 16ab711..c094c2c 100644 --- a/public/scripts/2_encryption.js +++ b/public/scripts/2_encryption.js @@ -1,16 +1,18 @@ -const alasql = require('alasql'); +const sql = require('alasql'); const openpgp = require('openpgp'); openpgp.initWorker({path: 'openpgp.worker.js'}); -let encrypted, decrypted; // REMEMBER: Remove testing variables (leaking) - +/** + * Generated localstorage database and tables + * @returns {boolean} + */ function setupDatabase() { - // REMEMBER: "key" and "type" are reserved names for SQL - alasql('CREATE localstorage DATABASE IF NOT EXISTS texx'); - alasql('ATTACH localStorage DATABASE texx AS db'); - alasql('CREATE TABLE IF NOT EXISTS db.own_keys (key_type STRING, key_data STRING)'); - alasql('CREATE TABLE IF NOT EXISTS db.keys (peer_id STRING, key_data STRING)'); - alasql('CREATE TABLE IF NOT EXISTS db.messages (id INT AUTO_INCREMENT, message STRING)'); + sql('CREATE localStorage DATABASE IF NOT EXISTS texx_ls'); + sql('ATTACH localStorage DATABASE texx_ls AS db'); + sql('SET AUTOCOMMIT ON'); + sql('CREATE TABLE IF NOT EXISTS db.own_keys (key_type STRING, key_data STRING)'); + sql('CREATE TABLE IF NOT EXISTS db.peer_keys (peer_id STRING, key_data STRING)'); + sql('CREATE TABLE IF NOT EXISTS db.messages (id INT AUTO_INCREMENT, message STRING)'); return true; } @@ -28,9 +30,9 @@ async function generateKeys(peerId, passphrase) { }; await openpgp.generateKey(options).then((key) => { - alasql(`INSERT INTO db.own_keys VALUES ("private_key", "${key.privateKeyArmored}")`); - alasql(`INSERT INTO db.own_keys VALUES ("public_key", "${key.publicKeyArmored}")`); - alasql(`INSERT INTO db.own_keys VALUES ("revocation_certificate", "${key.revocationCertificate}")`); + sql(`INSERT INTO db.own_keys VALUES ("private_key", "${key.privateKeyArmored}")`); + sql(`INSERT INTO db.own_keys VALUES ("public_key", "${key.publicKeyArmored}")`); + sql(`INSERT INTO db.own_keys VALUES ("revocation_certificate", "${key.revocationCertificate}")`); console.log('[LOG] Successfully generated and stored keys!'); }); } @@ -40,7 +42,7 @@ async function generateKeys(peerId, passphrase) { * @returns {string} */ function getPrivateKey() { - const privateKey = alasql('SELECT key_data FROM db.own_keys WHERE key_type = "private_key" LIMIT 1'); + const privateKey = sql('SELECT key_data FROM db.own_keys WHERE key_type = "private_key" LIMIT 1'); return privateKey.length > 0 ? privateKey[0]['key_data'] : ''; } @@ -49,7 +51,7 @@ function getPrivateKey() { * @returns {string} */ function getPublicKey() { - const publicKey = alasql('SELECT key_data FROM db.own_keys WHERE key_type = "public_key" LIMIT 1'); + const publicKey = sql('SELECT key_data FROM db.own_keys WHERE key_type = "public_key" LIMIT 1'); return publicKey.length > 0 ? publicKey[0]['key_data'] : ''; } @@ -58,31 +60,32 @@ function getPublicKey() { * @returns {string} */ function getRevocationCertificate() { - const revocationCertificate = alasql('SELECT key_data FROM db.own_keys WHERE key_type = "revocation_certificate" LIMIT 1'); + const revocationCertificate = sql('SELECT key_data FROM db.own_keys WHERE key_type = "revocation_certificate" LIMIT 1'); return revocationCertificate.length > 0 ? revocationCertificate[0]['key_data'] : ''; } /** + * /** * Encrypts the data with a public key (e.g the one of the peer with which you're chatting) * @param data * @param publicKey - * @returns {Promise<void>} + * @returns {Promise<String>} */ async function encrypt(data, publicKey) { + console.log(publicKey); //const privateKeyObj = (await openpgp.key.readArmored(privateKey)).keys[0]; //await privateKeyObj.decrypt(passphrase); const options = { message: openpgp.message.fromText(data), publicKeys: (await openpgp.key.readArmored(publicKey)).keys, - //privateKeys: [privateKeyObj] TODO: Use private key for signing + //privateKeys: [privateKeyObj] // TODO: Use private key for signing }; - await openpgp.encrypt(options).then(ciphertext => { - encrypted = ciphertext.data; - console.log(encrypted); - //return encrypted; // TODO: Return encrypted from async function - }) + return await openpgp.encrypt(options).then(ciphertext => { + console.log(ciphertext.data); + return ciphertext.data; + }); } /** @@ -91,7 +94,7 @@ async function encrypt(data, publicKey) { * @param publicKey * @param privateKey * @param passphrase - * @returns {Promise<void>} + * @returns {Promise<String>} */ async function decrypt(data, publicKey, privateKey, passphrase) { const privateKeyObj = (await openpgp.key.readArmored(privateKey)).keys[0]; @@ -103,11 +106,7 @@ async function decrypt(data, publicKey, privateKey, passphrase) { privateKeys: [privateKeyObj] }; - await openpgp.decrypt(options).then(plaintext => { - decrypted = plaintext.data; - console.log(plaintext.data); - //return plaintext.data - }) + return await openpgp.decrypt(options).then(plaintext => plaintext.data) } /** @@ -126,18 +125,29 @@ function isEncrypted() { * @param peerId * @param key */ -function storePublicKey(peerId, key) { - alasql(`INSERT INTO db.keys VALUES ("${peerId}", "${key}")`); +function storePeerPublicKey(peerId, key) { + console.log(peerId); + console.log(key); + sql(`INSERT INTO db.peer_keys VALUES ("${peerId}", "${key}")`); console.log('[LOG] Stored public key of ' + peerId); } /** + * Gets the public key of a peer + * @param peerId + */ +function getPeerPublicKey(peerId) { + const publicKey = sql(`SELECT key_data FROM db.peer_keys WHERE peer_id = "${peerId}" LIMIT 1`); + return publicKey.length > 0 ? publicKey[0]['key_data'] : ''; +} + +/** * Just a general test case */ function testEncryption() { generateKeys('test_id', 'supersecure').then(() => { - encrypt('The meaning of life', getPublicKey()).then(() => { - decrypt(encrypted, getPublicKey(), getPrivateKey(), 'supersecure').then(() => { + encrypt('The meaning of life', getPublicKey()).then(encrypted => { + decrypt(encrypted, getPublicKey(), getPrivateKey(), 'supersecure').then(decrypted => { if (decrypted === 'The meaning of life') console.log("YEEHA, Test succeeded!") }) @@ -152,5 +162,8 @@ exports.getPublic = getPublicKey; exports.encrypt = encrypt; exports.decrypt = decrypt; exports.check = isEncrypted; -exports.store = storePublicKey; +exports.store = storePeerPublicKey; +exports.get = getPeerPublicKey; exports.test = testEncryption; + +window.sql = sql; // For debugging diff --git a/public/scripts/chat.js b/public/scripts/chat.js index ec27a11..6c5271e 100644 --- a/public/scripts/chat.js +++ b/public/scripts/chat.js @@ -8,7 +8,7 @@ const peerId = nanoid(); // setup encryption if (encryption.setup() && encryption.check()) { - // TODO: Ask for password + // TODO: Ask for passphrase chat(); } else { console.log('[LOG] No existing keys found! Generating...'); @@ -23,8 +23,9 @@ function chat() { peer.on('error', err => console.error(err)); peer.on('connection', conn => { connectedPeer = conn; - console.log('[LOG] Connected with', conn.peer); - conn.on('data', message => receivedMessage(message)); + console.log('[LOG] Connected with', connectedPeer.peer); + connectedPeer.on('open', () => transferKey(encryption.getPublic())); + connectedPeer.on('data', message => receivedMessage(message)); }); /** @@ -36,13 +37,8 @@ function chat() { console.log('[LOG] Connecting to', id); console.log('[LOG] Your connection ID is', connectionId); connectedPeer = peer.connect(id, {label: connectionId, reliable: true}); - - // setup listener - connectedPeer.on('open', () => { - // TODO: Activate chat or sth - transferKey(encryption.getPublic()); - }); - + console.log('[LOG] Connected with', connectedPeer.peer); + connectedPeer.on('open', () => transferKey(encryption.getPublic())); connectedPeer.on('data', message => receivedMessage(message)) } @@ -52,8 +48,10 @@ function chat() { */ function sendMessage(message) { console.log(`[LOG] Sending message ${message} to ${connectedPeer.peer}`); - connectedPeer.send({type: 'text', data: message}); - receivedMessage(message, true); + encryption.encrypt(message, encryption.get(connectedPeer.peer)).then(encrypted => { + connectedPeer.send({type: 'text', data: encrypted}); + receivedMessage(message, true); + }) } /** @@ -74,11 +72,10 @@ function chat() { if (self) { $('#messages').append(`<span style="color: green">${message}</span><br>`); } else { - if (message.type === 'text') - $('#messages').append(`${message.data}<br>`); - else if (message.type === 'key') { - console.log(connectedPeer.peer); - console.log(peer.connections); + if (message.type === 'text') { + encryption.decrypt(message.data, encryption.get(connectedPeer.peer), encryption.getPrivate(), 'supersecure') + .then(plaintext => $('#messages').append(`${plaintext}<br>`)); + } else if (message.type === 'key') { encryption.store(connectedPeer.peer, message.data) } } |