Merge branch 'master' of github.com:Jlavatai/strapp
[henge/kiak.git] / strappCrypto.js
1 /**
2 * @file Management for bootstrapp cryptography
3 * @desc Makes keys, encrypts and decrypts messages
4 *
5 * @author Jordan Lavatai and Ken Grimes
6 * @version 0.0.1
7 * @license AGPL-3.0
8 * @copyright Strapp.io
9 */
10
11 /* TODO: Replace with filesystem operations */
12 import {setItem, getItem} from "localForage"
13
14 /** @func Generates a CryptoKey and returns a SHA-256 client key
15 * @desc Utilizes Web Crypto to create a CryptoKey using RSA specification.
16 * Stores both public and private representation of the key and returns
17 * the public key
18 * @return {String} clientKey
19 */
20 function generateKey() {
21 crypto.subtle.generateKey(
22 { name:'RSA-OAEP',
23 modulusLength: 2048,
24 publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
25 hash: {name: "SHA-256"}
26 },
27 true,
28 ['encrypt', 'decrypt']
29 ).then((cryptoKey) => {
30 /* TODO: Do we need to store the private key as well? */
31 crypto.subtle.exportKey('jwk', cryptoKey)
32 .then((exportedKey) => {
33 setItem('publicKey', exportedKey.publicKey)
34 setItem('privateKey', exportedKey.privateKey)
35 console.log('public key is' + getItem('publicKey'))
36 console.log('private key is' + getItem('privateKey'))
37 return exportedKey.publicKey
38 })
39 })
40 }
41
42 /** @func Encrypts data with a public key assuming RSA
43 * @desc https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt
44 * @arg {String} Public Key
45 * @return {Object} The encrypted data as a promise
46 */
47 function encryptData(publicKey, data) {
48 return crypto.subtle.encrypt({"name": "RSA-OAEP"})
49 }
50 /** @func Decrypts data with a private key
51 * @desc https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/decrypt
52 * @arg {String} Private key to decrypt data
53 * @return {Object} The decrypted data as a promise
54 */
55 function decryptData(privateKey, cipherText) {
56 /* TODO: Pass in private key or get it from localForage? */
57 return crypto.subtle.decrypt({"name":"RSA-OAEP"}, privateKey, cipherText)
58 }
59
60