无法使用crypto.createDecipheriv()正确解密文件。文件大小为0字节

时间:2019-02-28 12:45:49

标签: javascript node.js cryptography

我正在尝试使用流对文件进行加密/解密。我不确定如何正确执行。解密文件的大小为0 bytes

我找不到有关如何加密/解密流的任何适当信息。我发现的所有模块和文章都使用了非常过时的方法(它们使用了不赞成使用的方法),并且大部分内容展示了如何加密/解密strings而不是files

更新

  • 显然,在某些系统目录(例如/DesktopC:/等)中,我只能得到0个字节的文件。我该如何解决?我将在Electron应用程序中运行此代码。

  • 而且,我运行的这段代码安全吗?我在做错什么吗?

代码:

const crypto = require('crypto')
const fs = require('fs')

const path = 'C:/testImage'
const algorithm = 'aes-256-cbc'
const keyLength = 32
const password = '1234'
const salt = crypto.randomBytes(32)
const iv = crypto.randomBytes(16)
const key = crypto.scryptSync(password, salt, keyLength)


function encrypt() {
  const cipher = crypto.createCipheriv(algorithm, key, iv)
  const input = fs.createReadStream(path + '.png')
  const output = fs.createWriteStream(path + '.enc')
  input.pipe(cipher).pipe(output)

  cipher.on('end', () => {
    console.log('encrypted');
    decrypt()
  })
}


function decrypt() {
  const decipher = crypto.createDecipheriv(algorithm, key, iv)
  const input = fs.createReadStream(path + '.enc')
  const output = fs.createWriteStream(path + '_dec.png')
  input.pipe(decipher).pipe(output)

  decipher.on('end', () => {
    console.log('decrypted');
  })
}


encrypt()

2 个答案:

答案 0 :(得分:1)

我尝试了您的脚本,它可以工作。 (https://ibb.co/4Jvv6v1

您是否尝试在Windows上以管理员身份执行脚本?

如果您使用的是GitBash或PowerShell,请以管理员身份运行它,然后:

node your-script.js

答案 1 :(得分:0)

我发现了问题。我必须更改:

此: decipher.on('end', () => {

对此: output.on('finish', () => {

它现在可以工作。