insomnia/app/backend/sync/crypt.js
Gregory Schier 46d3719b99 Sync Proof of Concept (#33)
* Maybe working POC

* Change to use remote url

* Other URL too

* Some logic

* Got the push part working

* Made some updates

* Fix

* Update

* Add status code check

* Stuff

* Implemented new sync api

* A bit more robust

* Debounce changes

* Change timeout

* Some fixes

* Remove .less

* Better error handling

* Fix base url

* Support for created vs updated docs

* Try silent

* Silence removal too

* Small fix after merge

* Fix test

* Stuff

* Implement key generation algorithm

* Tidy

* stuff

* A bunch of stuff for the new API

* Integrated the session stuff

* Stuff

* Just started on encryption

* Lots of updates to encryption

* Finished createResourceGroup function

* Full encryption/decryption working (I think)

* Encrypt localstorage with sessionID

* Some more

* Some extra checks

* Now uses separate DB. Still needs to be simplified a LOT

* Fix deletion bug

* Fixed unicode bug with encryption

* Simplified and working

* A bunch of polish

* Some stuff

* Removed some workspace meta properties

* Migrated a few more meta properties

* Small changes

* Fix body scrolling and url cursor jumping

* Removed duplication of webpack port

* Remove workspaces reduces

* Some small fixes

* Added sync modal and opt-in setting

* Good start to sync flow

* Refactored modal footer css

* Update sync status

* Sync logger

* A bit better logging

* Fixed a bunch of sync-related bugs

* Fixed signup form button

* Gravatar component

* Split sync modal into tabs

* Tidying

* Some more error handling

* start sending 'user agent

* Login/signup error handling

* Use real UUIDs

* Fixed tests

* Remove unused function

* Some extra checks

* Moved cloud sync setting to about page

* Some small changes

* Some things
2016-10-21 10:20:36 -07:00

355 lines
9.2 KiB
JavaScript

import HKDF from 'hkdf';
import sjcl from 'sjcl';
import srp from 'srp';
import forge from 'node-forge';
const DEFAULT_BYTE_LENGTH = 32;
const DEFAULT_PBKDF2_ITERATIONS = 1E5; // 100,000
/**
* Generate hex signing key used for AES encryption
*
* @param pass
* @param email
* @param salt
*/
export async function deriveKey (pass, email, salt) {
const combinedSalt = await _hkdfSalt(salt, email);
return _pbkdf2Passphrase(pass, combinedSalt);
}
/**
* Encrypt with RSA256 public key
*
* @param publicKeyJWK
* @param plaintext
* @return String
*/
export function encryptRSAWithJWK (publicKeyJWK, plaintext) {
if (publicKeyJWK.alg !== 'RSA-OAEP-256') {
throw new Error('Public key algorithm was not RSA-OAEP-256');
} else if (publicKeyJWK.kty !== 'RSA') {
throw new Error('Public key type was not RSA');
} else if (!publicKeyJWK.key_ops.find(o => o === 'encrypt')) {
throw new Error('Public key does not have "encrypt" op');
}
const encodedPlaintext = encodeURIComponent(plaintext);
const n = _b64UrlToBigInt(publicKeyJWK.n);
const e = _b64UrlToBigInt(publicKeyJWK.e);
const publicKey = forge.rsa.setPublicKey(n, e);
const encrypted = publicKey.encrypt(encodedPlaintext, 'RSA-OAEP', {
md: forge.md.sha256.create()
});
return forge.util.bytesToHex(encrypted);
}
export function decryptRSAWithJWK (privateJWK, encryptedBlob) {
const n = _b64UrlToBigInt(privateJWK.n);
const e = _b64UrlToBigInt(privateJWK.e);
const d = _b64UrlToBigInt(privateJWK.d);
const p = _b64UrlToBigInt(privateJWK.p);
const q = _b64UrlToBigInt(privateJWK.q);
const dP = _b64UrlToBigInt(privateJWK.dp);
const dQ = _b64UrlToBigInt(privateJWK.dq);
const qInv = _b64UrlToBigInt(privateJWK.qi);
const privateKey = forge.rsa.setPrivateKey(n, e, d, p, q, dP, dQ, qInv);
const bytes = forge.util.hexToBytes(encryptedBlob);
const decrypted = privateKey.decrypt(bytes, 'RSA-OAEP', {
md: forge.md.sha256.create()
});
return decodeURIComponent(decrypted);
}
/**
* Encrypt data using symmetric key
*
* @param jwkOrKey JWK or string representing symmetric key
* @param plaintext string of data to encrypt
* @param additionalData any additional public data to attach
* @returns {{iv, t, d, ad}}
*/
export function encryptAES (jwkOrKey, plaintext, additionalData = '') {
// TODO: Add assertion checks for JWK
const rawKey = typeof jwkOrKey === 'string' ? jwkOrKey : _b64UrlToHex(jwkOrKey.k);
const key = forge.util.hexToBytes(rawKey);
const iv = forge.random.getBytesSync(12);
const cipher = forge.cipher.createCipher('AES-GCM', key);
// Plaintext could contain weird unicode, so we have to encode that
const encodedPlaintext = encodeURIComponent(plaintext);
cipher.start({additionalData, iv, tagLength: 128});
cipher.update(forge.util.createBuffer(encodedPlaintext));
cipher.finish();
return {
iv: forge.util.bytesToHex(iv),
t: forge.util.bytesToHex(cipher.mode.tag),
d: forge.util.bytesToHex(cipher.output),
ad: forge.util.bytesToHex(additionalData)
};
}
/**
* Decrypt AES using a key
*
* @param jwkOrKey JWK or string representing symmetric key
* @param message
* @returns String
*/
export function decryptAES (jwkOrKey, message) {
// TODO: Add assertion checks for JWK
const rawKey = typeof jwkOrKey === 'string' ? jwkOrKey : _b64UrlToHex(jwkOrKey.k);
const key = forge.util.hexToBytes(rawKey);
// ~~~~~~~~~~~~~~~~~~~~ //
// Decrypt with AES-GCM //
// ~~~~~~~~~~~~~~~~~~~~ //
const decipher = forge.cipher.createDecipher('AES-GCM', key);
decipher.start({
iv: forge.util.hexToBytes(message.iv),
tagLength: message.t.length * 4,
tag: forge.util.hexToBytes(message.t),
additionalData: forge.util.hexToBytes(message.ad)
});
decipher.update(forge.util.createBuffer(forge.util.hexToBytes(message.d)));
if (decipher.finish()) {
return decodeURIComponent(decipher.output.toString())
} else {
throw new Error('Failed to decrypt data')
}
}
/**
* Generate a random salt in hex
*
* @returns {string}
*/
export function getRandomHex (bytes = DEFAULT_BYTE_LENGTH) {
return forge.util.bytesToHex(forge.random.getBytesSync(bytes));
}
/**
* Generate a random account Id
*
* @returns {string}
*/
export function generateAccountId () {
return `act_${getRandomHex(DEFAULT_BYTE_LENGTH)}`;
}
/**
* Generate a random key
*
* @returns {Promise}
*/
export function srpGenKey () {
return new Promise((resolve, reject) => {
srp.genKey((err, secret1Buffer) => {
if (err) {
reject(err);
} else {
resolve(secret1Buffer.toString('hex'))
}
});
})
}
/**
* Generate a random AES256 key for use with symmetric encryption
*/
export async function generateAES256Key () {
const c = window.crypto;
const subtle = c ? c.subtle || c.webkitSubtle : null;
if (subtle) {
console.log('-- Using Native AES Key Generation --');
const key = await subtle.generateKey(
{name: 'AES-GCM', length: 256},
true,
['encrypt', 'decrypt']
);
return subtle.exportKey('jwk', key);
} else {
console.log('-- Using Falback Forge AES Key Generation --');
const key = forge.util.bytesToHex(forge.random.getBytesSync(32));
return {
kty: 'oct',
alg: 'A256GCM',
ext: true,
key_ops: ['encrypt', 'decrypt'],
k: _hexToB64Url(key),
};
}
}
/**
* Generate RSA keypair JWK with 2048 bits and exponent 0x10001
*
* @returns Object
*/
export async function generateKeyPairJWK () {
// NOTE: Safari has crypto.webkitSubtle, but does not support RSA-OAEP-SHA256
const subtle = window.crypto && window.crypto.subtle;
if (subtle) {
console.log('-- Using Native RSA Generation --');
const pair = await subtle.generateKey({
name: 'RSA-OAEP',
publicExponent: new Uint8Array([1, 0, 1]),
modulusLength: 2048,
hash: 'SHA-256'
},
true,
['encrypt', 'decrypt']
);
return {
publicKey: await subtle.exportKey('jwk', pair.publicKey),
privateKey: await subtle.exportKey('jwk', pair.privateKey)
};
} else {
console.log('-- Using Forge RSA Generation --');
const pair = forge.pki.rsa.generateKeyPair({bits: 2048, e: 0x10001});
const privateKey = {
alg: 'RSA-OAEP-256',
kty: 'RSA',
key_ops: ['decrypt'],
ext: true,
d: _bigIntToB64Url(pair.privateKey.d),
dp: _bigIntToB64Url(pair.privateKey.dP),
dq: _bigIntToB64Url(pair.privateKey.dQ),
e: _bigIntToB64Url(pair.privateKey.e),
n: _bigIntToB64Url(pair.privateKey.n),
p: _bigIntToB64Url(pair.privateKey.p),
q: _bigIntToB64Url(pair.privateKey.q),
qi: _bigIntToB64Url(pair.privateKey.qInv)
};
const publicKey = {
alg: 'RSA-OAEP-256',
kty: 'RSA',
key_ops: ['encrypt'],
e: _bigIntToB64Url(pair.publicKey.e),
n: _bigIntToB64Url(pair.publicKey.n),
};
return {privateKey, publicKey};
}
}
// ~~~~~~~~~~~~~~~~ //
// Helper Functions //
// ~~~~~~~~~~~~~~~~ //
/**
* Combine email and raw salt into usable salt
*
* @param rawSalt
* @param rawEmail
* @returns {Promise}
*/
function _hkdfSalt (rawSalt, rawEmail) {
return new Promise(resolve => {
const hkdf = new HKDF('sha256', rawSalt, rawEmail);
hkdf.derive('', DEFAULT_BYTE_LENGTH, buffer => resolve(buffer.toString('hex')));
})
}
/**
* Convert a JSBN BigInteger to a URL-safe version of base64 encoding. This
* should only be used for encoding JWKs
*
* @param n BigInteger
* @returns {string}
*/
function _bigIntToB64Url (n) {
return _hexToB64Url(n.toString(16));
}
function _hexToB64Url (h) {
const bytes = forge.util.hexToBytes(h);
return btoa(bytes)
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
}
function _b64UrlToBigInt (s) {
return new forge.jsbn.BigInteger(_b64UrlToHex(s), 16);
}
function _b64UrlToHex (s) {
const b64 = s.replace(/-/g, '+').replace(/_/g, '/');
return forge.util.bytesToHex(atob(b64));
}
window.b64urltohex = _b64UrlToHex;
window.forge = forge;
/**
* Derive key from password
*
* @param passphrase
* @param salt hex representation of salt
*/
async function _pbkdf2Passphrase (passphrase, salt) {
if (window.crypto && window.crypto.subtle) {
console.log('-- Using native PBKDF2 --');
const k = await window.crypto.subtle.importKey(
'raw',
Buffer.from(passphrase, 'utf8'),
{name: 'PBKDF2'},
true,
['deriveBits']
);
const algo = {
name: 'PBKDF2',
salt: new Buffer(salt, 'hex'),
iterations: DEFAULT_PBKDF2_ITERATIONS,
hash: 'SHA-256'
};
const derivedKeyRaw = await window.crypto.subtle.deriveBits(algo, k, DEFAULT_BYTE_LENGTH * 8);
return new Buffer(derivedKeyRaw).toString('hex');
} else {
console.log('-- Using SJCL PBKDF2 --');
const derivedKeyRaw = sjcl.misc.pbkdf2(
passphrase,
sjcl.codec.hex.toBits(salt),
DEFAULT_PBKDF2_ITERATIONS,
DEFAULT_BYTE_LENGTH * 8,
sjcl.hash.sha1
);
return sjcl.codec.hex.fromBits(derivedKeyRaw);
// NOTE: SJCL (above) is about 10x faster than Forge
// const derivedKeyRaw = forge.pkcs5.pbkdf2(
// passphrase,
// forge.util.hexToBytes(salt),
// DEFAULT_PBKDF2_ITERATIONS,
// DEFAULT_BYTE_LENGTH,
// forge.md.sha256.create()
// );
// const derivedKey = forge.util.bytesToHex(derivedKeyRaw);
}
}