반응형
express를 이용한 첨부파일 암호화 및 S3 업로드
1. router POST 업로드 호출 후
var s3 = require('../util/awsFileUpload')
router.post('/fileupload', function(req, res, next){
s3.encUpload(req, res, function(err, result){
if(err){
res.send('error').end();
} else {
res.send('success image file').end();
}
})
});
awsFileUpload.js 파일
let multer = require('multer')
var storage = multer.memoryStorage()
const upload = multer({storage: storage, limits: { fileSize: 10 * 1024 * 1024 }})
let AWS = require('aws-sdk')
var cryptoFile = require('../util/crypto')
AWS.config.loadFromPath(__dirname + '/../config/awsconfig.json')
let s3 = new AWS.S3()
var s3Upload = {
encUpload : function(req, res, callback) {
var uploads = upload.single('uploadfile');
uploads(req, res, function(err){
var file = req.file;
file.buffer = cryptoFile.buffercipher(file.buffer);
var fileName = new Date().valueOf() +".enc";
var params = {
Bucket: '버킷명',
Key: fileName,
Body: file.buffer,
ACL: 'public-read', // your permisions
};
s3.putObject(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
callback(err, data);
});
});
}
}
module.exports = s3Upload
crypto.js
var crypto = require('crypto')
var multer = require('multer')
const fs = require('fs');
var key = new Buffer('암호화키', 'hex');
const cipher = crypto.createCipher('aes-256-cbc', key)
const decipher = crypto.createDecipher('aes-256-cbc', key)
var cryptoUtil = {
buffercipher: function(bufferData) {
var base64 = bufferData.toString('base64')
var enData = cipher.update(base64);
return enData;
},
s3decipher: function(data) {
var binary = new Buffer(data,'base64')
var decrypted = decipher.update(binary, 'binary', 'utf8')
return decrypted;
},
}
module.exports = cryptoUtil;
awsconfig.json S3 키발급
{
"accessKeyId": "accessKey",
"secretAccessKey": "secret키",
"region": "지역"
}
반응형