0

I am retrieving a file from IPFS and storing it as an array buffer in the browser. I want to decrypt it in a stream and save it locally. During storage, I encrypted it like this:

    const iv = crypto.randomBytes(16);
    const cipher = crypto.createCipheriv('aes-256-ctr', key, iv, null);
    const input = fs.createReadStream(inputFilePath);
    const storage = makeStorageClient();
    const keyString = new Int32Array(key).toString();
    const cid = await storage.put([{ name: fileName, stream: () => input.pipe(cipher) }]);

Now, I want to do the reverse in the browser.

I can't access the crypto module in the browser as far as I can tell, otherwise I would do this:

        const retrieved = await ipfs.cat(cid+'/'+link.name);
        const decipher = crypto.createDecipheriv('aes-256-ctr', key, iv, null);
        const input = new ReadableStream(retrieved);
        const output = streamSaver.createWriteStream(link.name);
        const finished = await input.pipe(decipher).pipe(output);

SubtleCrypto.decrypt(algorithm, key, data) seems promising, but to decrypt aes-256-ctr, I need to pass a params object into it. This object requires a counter and length. Does anyone know how I can get those? Is there a better way to decrypt in a stream in the browser?

Boris K
  • 3,442
  • 9
  • 48
  • 87
  • It looks like you throw away your IV that you used for encryption. The decrypter needs this, the usual technique is to prepend it to the cipher. The IV does not need to be kept secret. The IV is essentially the initial counter for CTR mode, thus it should probably be abbreviated IC rather than IV. – President James K. Polk Sep 22 '22 at 21:20
  • No, I'm passing the IV, I just didn't spell it out here. – Boris K Sep 22 '22 at 21:28
  • Well, that's the only thing in the params object, you can use 64 for the counter bits or 128, you're never going to come close to having that much data to process. – President James K. Polk Sep 22 '22 at 21:30
  • But how do I pipe the stream through the decipher function with subtle crypto? – Boris K Sep 22 '22 at 21:34

0 Answers0