天天看點

nodejs向加密檔案指定位置插入内容

需求:

  檔案加密,将加密密鑰之類的東西放在加密檔案之前,類似于給檔案增加一個頭部資訊,在解密的時候從檔案這個頭部資訊裡拿到這些密鑰之類的東西,請求擷取解密的code之類的東西,然後解密加密的檔案。比如下

nodejs向加密檔案指定位置插入内容

問題:

  不能向檔案的指定位置插入内容,如果直接将檔案記錄指針移動到中間某位置後開始輸出,則新輸出的内容會覆寫檔案中原有的内容,如果需要向指定位置插入内容,程式需要先把插入點後面的内容讀入緩沖區,等把需要插入的資料寫入檔案後,再将緩沖區的内容追加到檔案後面。

方案及插入步驟:

  1、建立臨時檔案,儲存被插入檔案的插入點後面的内容;

  2、再重新定位到插入點,将需要插入的内容添加到檔案後面;

  3、最後将臨時檔案的内容添加到檔案後面。

  下面是一個簡單的demo

const crypto = require('crypto')
const fs = require('fs')
const path = require('path')
let key = '54F0853FD5D8D2FD61CE33309B0D0273'
let iv = 'A19820BCE43576DF'

function aesEncryptNew (buff, key, iv) {
  let cipher = crypto.createCipheriv('aes-256-cbc', key, iv)
  return cipher.update(buff, '', 'hex')
}
function aesDecryptNew (buff, key, iv) {
  let decipher = crypto.createDecipheriv('aes-256-cbc', key, iv)
  return decipher.update(buff, 'hex')
}

function encryptFile (filepath, filename) {
  let _path = path.join(filepath, filename)
  let buff = fs.readFileSync(_path)
  let buffEnc = aesEncryptNew(buff, key, iv)
  let _newPath = _path + '.mc'// 建立一個可以寫入的流,寫入到檔案 output.txt 中
  var writerStream = fs.createWriteStream(_newPath)
  // 使用 utf8 編碼寫入資料
  writerStream.write(key, 'utf8')
  writerStream.write(Buffer.from(buffEnc, 'hex'), 'hex')
  // 标記檔案末尾
  writerStream.end()
  // 處理流事件 --> data, end, and error
  writerStream.on('finish', function () {
    console.log('寫入完成。')
  })
}

function decryptFile (filepath, filename) {
  let _path = path.join(filepath, filename)
  let hexContent = fs.readFileSync(_path)
  let bufferFile = hexContent.slice(32, hexContent.length)
  let deHex = aesDecryptNew(bufferFile, key, iv)
  let _newPath = _path.replace(/.mc/g, '')
  fs.writeFileSync(_newPath, Buffer.from(deHex, 'hex'))
}

export {
  encryptFile,
  decryptFile
}