Created
September 2, 2021 22:15
-
-
Save victorfei/cb53f883ffbeaef36cbbfcf15bbca544 to your computer and use it in GitHub Desktop.
ipfs encrypt write, decrypt read
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Encryptes and writes string to ipfs. Retrieve and decrypts it. | |
var msg = 'begin r/w operation onto ipfs'; | |
console.log(msg); | |
const crypto = require('crypto'); | |
const ipfs = require('ipfs-core'); | |
const { exit } = require('process'); | |
const algo = 'aes-256-ctr'; | |
let key = 'OrmiPrivateKey'; | |
key = crypto.createHash('sha256').update(key).digest('base64').substr(0, 32); | |
console.log(key); | |
const encrypt = (buffer) => { | |
// Create an initialization vector | |
const iv = crypto.randomBytes(16); | |
// Create a new cipher using the algorithm, key, and iv | |
const cipher = crypto.createCipheriv(algo, key, iv); | |
// Create the new (encrypted) buffer | |
const result = Buffer.concat([iv, cipher.update(buffer), cipher.final()]); | |
return result; | |
}; | |
const decrypt = (encrypted) => { | |
// Get the iv: the first 16 bytes | |
const iv = encrypted.slice(0, 16); | |
// Get the rest | |
encrypted = encrypted.slice(16); | |
// Create a decipher | |
const decipher = crypto.createDecipheriv(algo, key, iv); | |
// Actually decrypt it | |
const result = Buffer.concat([decipher.update(encrypted), decipher.final()]); | |
return result; | |
}; | |
const plain = Buffer.from('Hello Ormi'); | |
const encrypted = encrypt(plain); | |
console.log('Encrypted:', encrypted.toString()); | |
const decrypted = decrypt(encrypted); | |
console.log('Decrypted:', decrypted.toString()); | |
// ---- ipfs write operations below --- | |
// const ipfs_wr = async (content) => { | |
// const ipfs_node = await ipfs.create(); | |
// const { cid } = await ipfs_node.add(content); | |
// console.log('cid: ' + cid.toString()); | |
// }; | |
// ipfs_wr(encrypted).catch(e => { | |
// console.log('There has been a problem with your operation: ' + e.message); | |
// }); | |
// ---- ipfs read operations below --- | |
// cid: Qmb97zk39xuPbsSZ1rnJBYvkPWXuthj4LSHwp5rLLLUzWH | |
const cid = "Qmb97zk39xuPbsSZ1rnJBYvkPWXuthj4LSHwp5rLLLUzWH"; | |
const ipfs_rd = async (cid) => { | |
const ipfs_node = await ipfs.create(); | |
const stream = ipfs_node.cat(cid); | |
for await (const chunk of stream) { | |
console.info("from ipfs: " + decrypt(chunk).toString()); | |
} | |
} | |
ipfs_rd(cid).catch(e => { | |
console.log('There has been a problem with your operation: ' + e.message); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment