-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
220 lines (184 loc) · 5.75 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
const ipfsClient = require('ipfs-http-client');
const { globSource } = ipfsClient;
const ipfsEndPoint = 'http://localhost:5001'
const ipfs = ipfsClient(ipfsEndPoint);
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
////////////////////////////////
//////////// IPFS //////////////
////////////////////////////////
generateKeys()
// _testing()
async function uploadFileEncrypted(file, ipfspath) {
try {
const buff = fs.readFileSync(file);
const key = crypto.randomBytes(16).toString('hex'); // 16 bytes -> 32 chars
const iv = crypto.randomBytes(8).toString('hex'); // 8 bytes -> 16 chars
const ekey = encryptRSA(key); // 32 chars -> 684 chars
const ebuff = encryptAES(buff, key, iv);
const content = Buffer.concat([ // headers: encrypted key and IV (len: 700=684+16)
Buffer.from(ekey, 'utf8'), // char length: 684
Buffer.from(iv, 'utf8'), // char length: 16
Buffer.from(ebuff, 'utf8')
])
await ipfs.files.write(
ipfspath,
content,
{create: true, parents: true}
);
console.log('ENCRYPTION --------')
console.log('key:', key, 'iv:', iv, 'ekey:', ekey.length)
console.log('contents:', buff.length, 'encrypted:', ebuff.length)
console.log(' ')
} catch (err) {
console.log(err)
throw err;
}
}
async function toArray(asyncIterator) {
const arr=[];
for await(const i of asyncIterator) {
arr.push(i);
}
return arr;
}
async function downloadFileEncrypted(ipfspath) {
try {
let file_data = await ipfs.files.read(ipfspath)
let edata = []
for await (const chunk of file_data)
edata.push(chunk)
edata = Buffer.concat(edata)
const key = decryptRSA(edata.slice(0, 684).toString('utf8'))
const iv = edata.slice(684, 700).toString('utf8')
const econtent = edata.slice(700).toString('utf8')
const ebuf = Buffer.from(econtent, 'hex')
const content = decryptAES(ebuf, key, iv)
console.log(' ')
console.log('DECRYPTION --------')
console.log('key:', key, 'iv:', iv)
console.log('contents:', content.length, 'encrypted:', econtent.length)
console.log('downloaded:', edata.length)
return content
} catch (err) {
console.log(err)
throw err;
}
}
async function getUploadedFiles(ipfspath='/encrypted/') {
let files = []
const arr = await toArray(ipfs.files.ls(ipfspath))
for (let file of arr) {
if (file.type === 'directory') {
const inner = await getUploadedFiles(ipfspath + file.name + '/')
files = files.concat(inner)
} else {
files.push({
path: ipfspath + file.name,
size: file.size,
cid: file.cid.toString()
})
}
}
return files
}
function encryptAES(buffer, secretKey, iv) {
const cipher = crypto.createCipheriv('aes-256-ctr', secretKey, iv);
const data = cipher.update(buffer);
const encrypted = Buffer.concat([data, cipher.final()]);
return encrypted.toString('hex')
}
function decryptAES(buffer, secretKey, iv) {
const decipher = crypto.createDecipheriv('aes-256-ctr', secretKey, iv);
const data = decipher.update(buffer)
const decrpyted = Buffer.concat([data, decipher.final()]);
return decrpyted;
}
function generateKeys() {
if (fs.existsSync('private.pem') && fs.existsSync('public.pem'))
return;
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs1',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: '',
},
})
fs.writeFileSync('private.pem', privateKey)
fs.writeFileSync('public.pem', publicKey)
}
function encryptRSA(toEncrypt, pubkeyPath='public.pem') {
const absolutePath = path.resolve(pubkeyPath)
const publicKey = fs.readFileSync(absolutePath, 'utf8')
const buffer = Buffer.from(toEncrypt, 'utf8')
const encrypted = crypto.publicEncrypt(publicKey, buffer)
return encrypted.toString('base64')
}
function decryptRSA(toDecrypt, privkeyPath='private.pem') {
const absolutePath = path.resolve(privkeyPath)
const privateKey = fs.readFileSync(absolutePath, 'utf8')
const buffer = Buffer.from(toDecrypt, 'base64')
const decrypted = crypto.privateDecrypt(
{
key: privateKey.toString(),
passphrase: '',
},
buffer,
)
return decrypted.toString('utf8')
}
async function _testing() {
const file = 'package.json' // file to upload
const ipfspath = '/encrypted/data/' + file // ipfspath
// upload to ipfs path
await uploadFileEncrypted(file, ipfspath)
// download from ipfs path
const dl = await downloadFileEncrypted(ipfspath)
// to buffer
const buff = Buffer.from(dl, 'hex')
// save buffer to file
const outfile = ipfspath.replace(/\//g, '_');
console.log('writing:', outfile)
fs.writeFile(outfile, buff, function(err) {
if (err) throw err;
})
}
////////////////////////////////
///////// REST API /////////////
////////////////////////////////
const rest_port = 3000;
const express = require("express");
const app = express();
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get("/api/files", async (req, res, next) => {
try {
res.json(await getUploadedFiles())
} catch (e) {
// when /encrypted/ path not exists (~ no uploads): catch ipfs http error
res.json({error: e.toString()})
}
});
app.get(/^\/api\/file(\/.*)$/, async (req, res, next) => {
try {
const ipfspath = req.params[0];
const content = await downloadFileEncrypted(ipfspath)
res.send(content)
} catch (err) {
res.send('error: ' + err)
}
});
app.listen(rest_port, () => {
console.log("Server running on port 3000");
});
////////////////////////////////
////////////////////////////////
////////////////////////////////