1

my key : crypto.createHash('sha256').update('mySup3rC00lP4ssWord').digest()
my iv : crypto.randomBytes(16)
I try methods in this page : https://medium.com/@brandonstilson/lets-encrypt-files-with-node-85037bea8c0e

I use aes-256-cbc to decrypt a enc file , and this is my encrypting , file path is my location
C:\Users\芊吠\AppData\Roaming\vue-electron

function fileRead () {
  const AppendInitVect = require('../utils/appendInitVect') // 修改數據
  const path = app.getPath('userData') // appData的位址
  const cipher = crypto.createCipheriv('aes-256-cbc', Key, initVect)
  const appendInitVect = new AppendInitVect(initVect)
  const readStream = fs.createReadStream(path + '\\config.json') // 讀檔
  const gzipStream = zlib.createGzip() // 壓縮檔案
  const writeStream = fs.createWriteStream(path + '\\config.json.enc') // 新檔案
  readStream.pipe(gzipStream).pipe(cipher).pipe(appendInitVect).pipe(writeStream) // 壓縮再寫檔
}

this is my enc file , look at it is encrpt file! enter image description here



but my problem start ... When I decrypt this enc file , it will get error my iv is undefined ,
because readIv.on('data', (chunk) => { console.log('data') initVect = chunk // this is not work!!!!initVect is undefiend }) is not work , so my initVect get undefind, and how can I fix it?
this is my decrypting ...

function unFileRead () {
  const path = app.getPath('userData') // appData的位址
  const readIv = fs.createReadStream(path + '\\config.json.enc', { end: 15 }) // 創建iv讀取的steam
  console.log('decrpt path:', path + '\\config.json.enc')
  let initVect
  readIv.on('data', (chunk) => {
    console.log('data')
    initVect = chunk // this is not work!!!!initVect is undefiend
  })
  console.log('initVect:', initVect)
  readIv.on('close', () => {
    console.log('hello')
    const unzip = zlib.createUnzip()
    const readStream = fs.createReadStream(path + '\\config.json.enc', { start: 16 })
    const decipher = crypto.createDecipheriv('aes-256-cbc', Key, initVect)
    console.log('decipher:', decipher)
    const writeStream = fs.createWriteStream(path + '\\config.json.unenc') // 寫檔
    readStream.pipe(decipher).pipe(unzip).pipe(writeStream)
  })
}
haha861924
  • 17
  • 5

1 Answers1

1

The key to understand here is the difference between synchronous and asynchronous code. initVect is initialized to undefined synchronously, and is set asynchronously. So, when you're trying to console.log the initVect outside of the data and close callbacks, it will still be undefined since that line is run synchronously.

If you move your console.log('initVect:', initVect) underneath your console.log('hello'), you should see it.

Hope that helps.

bbstilson
  • 93
  • 1
  • 3
  • 7