I am experiencing data loss after decryting file. tried aes256, aes-192-cbc, aes-256-cbc.i am trying to upload encrypted file on IPFS and then when client wants it i need to download encrypted file then decrypt it and serve to client.. On analysis while encrypting any file i see that it size increases slightly than original file but when i decrypt encrypted file then obtained file size is less than original file.. even though with some data loss images do get served to client but bottom part is cutoff.. am i doing somthing wrong with streams?? i am just beginner in nodejs so please any suggestion would be appreciated./*****code****/const express = require('express'); const app = express();const bodyParser = require('body-parser');const fileUpload = require('express-fileupload');const fs = require('fs');const path = require('path');const ipfsClient = require('ipfs-http-client');const ipfsCluster = require('ipfs-cluster-api');const ipfs = new ipfsClient({host: 'localhost',port:'5001',protocol:'http'});const cluster = ipfsCluster('localhost', '9094', { protocol: 'http' });const crypto = require('crypto');const algorithm = 'aes256';//const iv = Buffer.alloc(16,'fsdfaldkfh');//const salt = Buffer.alloc(16,'saltysalt');//console.log(iv,salt);app.set('view engine','ejs');app.use(bodyParser.urlencoded({extended: true}));app.use(fileUpload());app.get('/',(req,res) =>{res.render('home');});app.get('/removeFile',(req,res)=>{res.render('separateRemove');});app.get('/downloadFile',(req,res)=>{res.render('download');})app.post('/downloadFile',async (req,res)=>{console.log(`hash to be downloaded is ${req.body.hash}`);const email = req.body.email;//const key = crypto.scryptSync(email,'salt',16);const decipher = crypto.createDecipher(algorithm, email);const cid = `/ipfs/${req.body.hash}`;const stream = ipfs.getReadableStream(cid);stream.on('data',(file)=>{if(JSON.stringify(file.path).includes("/")){const str = JSON.stringify(file.path).split("/")[1];console.log(str);const realFileName = str.split(`"`)[0];console.log(realFileName);const writeStream = fs.createWriteStream(`encrypted/${realFileName}`);file.content.on('data', (data) => {writeStream.write(data);});file.content.resume();file.content.on('end',()=>{writeStream.end();});writeStream.on('finish',()=>{console.log(typeof(realFileName));const encryptedFile = fs.createReadStream(`encrypted/${realFileName}`);const originalFile = fs.createWriteStream(`files/${realFileName}`);encryptedFile.pipe(decipher).pipe(originalFile);encryptedFile.on('end',()=>{originalFile.end();decipher.end();});originalFile.on('finish',()=>{const originalFilePath = path.join(__dirname,"files",realFileName);console.log(originalFilePath);res.setHeader('Content-Disposition', 'attachment; filename=' + realFileName);res.setHeader('Content-Transfer-Encoding', 'binary');res.setHeader('Content-Type', 'application/octet-stream');const readStream = fs.createReadStream(`files/${realFileName}`);readStream.pipe(res);res.sendFile(originalFilePath,function(err){if(err){console.log(err);}else{console.log(res.headersSent);fs.unlinkSync(`encrypted/${realFileName}`,err => {if(err){console.log(err);}});fs.unlinkSync(`files/${realFileName}`,err => {if(err){console.log(err);}});}});});});}});stream.on('error',(err)=>{console.log(err);res.send('failed');})})app.post('/removeFile',async (req,res)=>{console.log(req.body.hash);const cid = req.body.hash;const unpinStatus = await removeFileFromCluster(cid);console.log(unpinStatus);res.render('removeSuccess',{cid,unpinStatus});});app.post('/upload',(req,res)=>{console.log(req.files.file);console.log(req.body.email);const file = req.files.file;const fileName = req.files.file.name;const filePath = 'files/' + fileName;const email = req.body.email;console.log(filePath);file.mv(filePath, async(err)=>{if (err){console.log('error');return res.status(500).send(err);}const fileAdded = await addFileInCLuster(fileName,filePath, email);fs.unlink(filePath,(err)=>{if(err) console.log(err);})console.log(`this is returned from post /include method${JSON.stringify(fileAdded)}`)const fileHash = fileAdded[0].hash;const pathHash = fileAdded[1].hash;res.render('upload',{fileName,fileHash,pathHash});});});const addFile = async(fileName, filePath)=>{const file = fs.readFileSync(filePath);const fileAdded = await ipfs.add({path: fileName, content: file});const fileHash = fileAdded[0].hash;return fileHash;};const addFileInCLuster = async(fileName, filePath, email)=>{const password = email;//const key = crypto.scryptSync(password,'salt',16);const cipher = crypto.createCipher(algorithm, password);const file = fs.createReadStream(filePath);console.log(file);const fileEncrypted = file.pipe(cipher);console.log(cipher);const data =[{path: filePath,content: cipher}];const options = {"wrap-with-directory": false,};try{console.log(filePath);const fileAdded = await cluster.add(data,options);console.log(data);return fileAdded;}catch(err){console.log(err);}}const removeFileFromCluster = async (CID) =>{try{const fileStatus = await cluster.pin.rm(CID)}catch(err){console.log(err);return 'unsuccessful'}return 'successful';}const deleteFileFromServer = async(realFileName)=>{fs.unlink(`encrypted/${realFileName}`,(err)=>{if (err) throw err;console.log(`encrypted/${realfilename} was deleted`);});fs.unlink(`files/${realFileName}`,(err)=>{if (err) throw err;console.log(`files/${realfilename} was deleted`);});};app.listen(3000,()=>{console.log('server listening on 3000');})
Submitted July 17, 2019 at 05:37AM by AwalMukesh
No comments:
Post a Comment