1 | var fs = require('fs')
|
2 | , nacl = require('tweetnacl')
|
3 | , constants = require('../lib/constants')
|
4 | , libEphemeral = require('./ephemeral')
|
5 | , writeHeader = require('../utils/writeHeader')
|
6 | , makeNonce = require('../utils/makeNonce')
|
7 | , through = require('through')
|
8 | , assert = require('assert')
|
9 |
|
10 | nacl.stream = require('nacl-stream').stream
|
11 |
|
12 | function encrypt (inStream, recipient, nonce, totalSize, wallet, nopad, headers) {
|
13 | headers || (headers = {})
|
14 | var eph = libEphemeral.create(recipient, nonce, totalSize)
|
15 | var ended = false
|
16 | var encryptor = eph.createEncryptor(function isLast () {
|
17 | return ended
|
18 | })
|
19 | var bytesEncrypted = 0
|
20 | var hashStream = eph.createHmac()
|
21 | var header = Object.create(null)
|
22 | var outStream = through()
|
23 | encryptor.on('data', function (chunk) {
|
24 | outStream.write(chunk)
|
25 | })
|
26 | encryptor.once('end', function () {
|
27 | outStream.end()
|
28 | })
|
29 | inStream.pause()
|
30 | inStream.on('data', function (chunk) {
|
31 | encryptor.write(chunk)
|
32 | })
|
33 | inStream.once('end', function () {
|
34 | ended = true
|
35 | })
|
36 |
|
37 | function withHash () {
|
38 | if (wallet) {
|
39 | header['from-salty-id'] = wallet.pubkey.toBuffer().toString('base64')
|
40 | header['to-salty-id'] = recipient.toBuffer().toString('base64')
|
41 | if (header['to-salty-id'] === header['from-salty-id']) {
|
42 | header['to-salty-id'] = 'self'
|
43 | }
|
44 | }
|
45 | Object.keys(headers).forEach(function (k) {
|
46 | header[k] = headers[k]
|
47 | })
|
48 | if (wallet) {
|
49 | header['signature'] = wallet.sign(Buffer(writeHeader(header)), true).toString('base64')
|
50 | }
|
51 | var headerStr = writeHeader(header)
|
52 | var headerBuf = Buffer('\r\n\r\n' + headerStr + '\n')
|
53 | if (!nopad) {
|
54 | var padLength = Math.ceil(Math.random() * (constants.MAX_CHUNK - headerStr.length))
|
55 | var bytes = Buffer(padLength)
|
56 | for (var i = 0; i < padLength; i++) {
|
57 | bytes[i] = 0
|
58 | }
|
59 | headerBuf = Buffer.concat([headerBuf, bytes])
|
60 | }
|
61 | outStream.emit('header', header)
|
62 | encryptor.end(headerBuf)
|
63 | }
|
64 |
|
65 | hashStream.once('data', function (hash) {
|
66 | header['hash'] = hash.toString('base64')
|
67 | withHash()
|
68 | })
|
69 |
|
70 | setImmediate(function () {
|
71 | outStream.write(eph.toBuffer())
|
72 | inStream.pipe(hashStream)
|
73 | inStream.resume()
|
74 | })
|
75 |
|
76 | return outStream
|
77 | }
|
78 |
|
79 | module.exports = encrypt |
\ | No newline at end of file |