加密上传ipfs

在《基于js-ipfs-api实现ipfs的文件上传与下载》中已经实现了内容和文件上传ipfs,然后下载到本地。ipfs具有分布式存储和不可篡改性等优点,但隐私性较差,一旦上传到ipfs之后,用户就可以从任一ipfs节点的网关获取数据。一个比较简单的方法就是对内容采用对称加密之后,再进行存储。对于企业用户来说,可能还需要搭建私有的ipfs集群,文件加密之后存储到ipfs集群中。

AES加密模块(aes.js)

const fs = require('fs');
const crypto = require('crypto');
const algorithm = 'aes-256-ctr';

exports.encrypt = (buffer,password)=>{
    let cipher = crypto.createCipher(algorithm,password)
    let crypted = Buffer.concat([cipher.update(buffer),cipher.final()]);
    return crypted;
}
exports.decrypt = (buffer,password)=>{
    let decipher = crypto.createDecipher(algorithm,password)
    let dec = Buffer.concat([decipher.update(buffer) , decipher.final()]);
    return dec;
}

在《基于js-ipfs-api实现ipfs的文件上传与下载》的基础上,将内容加密之后再存储到ipfs中,并在下载之后对内容进行解密存储,这样ipfs服务器上存储的就是加密之后的数据,隐私和安全性得到提升。

const ipfsFile = require('./ipfsFile');
const fs = require('fs');
const crypto = require('crypto');
const AES = require('./aes');

//操作文件
let addPath = "./storage/add/onepiece.jpg";
let getPath = "./storage/get/onepiece.jpg";
let jsonPath = "./storage/get/json.txt";
//生成64位随机数作为密码
let password = crypto.randomBytes(32).toString("hex");
let buff = AES.encrypt(fs.readFileSync(addPath),password);

ipfsFile.add(buff).then((hash)=>{
    console.log(hash);
    console.log("http://localhost:8080/ipfs/"+hash);
    return ipfsFile.get(hash);
}).then((buff)=>{
    fs.writeFileSync(getPath,AES.decrypt(buff,password));
    console.log("file:"+getPath);
}).catch((err)=>{
    console.log(err);
})

//操作内容
let User = {
    "name":"naruto",
    "age":23,
    "level":"ss"
};
buff = AES.encrypt(Buffer.from(JSON.stringify(User)),password);
ipfsFile.add(buff).then((hash)=>{
    console.log(hash);
    console.log("http://localhost:8080/ipfs/"+hash);
    return ipfsFile.get(hash);
}).then((buff)=>{
    fs.writeFileSync(jsonPath,AES.decrypt(buff,password));
    console.log("file:"+jsonPath);
}).catch((err)=>{
    console.log(err);
})

加密存储之前

内容哈希:QmRfhWo4c24MWYXLxu69FcJBnKpmnjY9mN5nMiK8U9zNxB
ipfs官方网关地址:https://ipfs.io/ipfs/QmRfhWo4c24MWYXLxu69FcJBnKpmnjY9mN5nMiK8U9zNxB

图片哈希:QmVwdMZj5z1iSeKhmLPdZ6Diipn3krGZUnMLQMVxj4NjW7
ipfs官方网关地址:https://ipfs.io/ipfs/QmVwdMZj5z1iSeKhmLPdZ6Diipn3krGZUnMLQMVxj4NjW7

加密存储之后

内容哈希:QmZGLCo9hsVSgNVAbwPuST8nTma5pUfGDBYT28tmezMyaD
ipfs官方网关地址:http://ipfs.io/ipfs/QmZGLCo9hsVSgNVAbwPuST8nTma5pUfGDBYT28tmezMyaD

图片哈希:QmU4hVfhXUk9P5978TFL62vFAPVrvqaYGpA9VTqMKuzXQ6
ipfs官方网关地址:https://ipfs.io/ipfs/QmU4hVfhXUk9P5978TFL62vFAPVrvqaYGpA9VTqMKuzXQ6

猜你喜欢

转载自blog.csdn.net/koastal/article/details/78789943