1

校验文件最后四字节是否等于前面所有字节的累加值。

import { Modal } from "antd";

const buf2hex = (buffer: Buffer) => {
  return Array.prototype.map
    .call(new Uint8Array(buffer), (x) => ("00" + x.toString(16)).slice(-2))
    .join("");
};

/** 文件校验检查 */
export const otaFileCheck = (originFileObj: Blob) => {
  return new Promise((resolve, reject) => {
    var reader = new FileReader();
    reader.readAsArrayBuffer(originFileObj);
    reader.onload = function () {
      const result = this.result as Buffer;
      const joindata = buf2hex(result);
      const sumArr = [];
      for (let i = 0; i < joindata.length / 2; i++) {
        sumArr.push(joindata[i * 2] + joindata[i * 2 + 1]);
      }
      const fileHexCheck = `${sumArr[sumArr.length - 4]}${
        sumArr[sumArr.length - 3]
      }${sumArr[sumArr.length - 2]}${sumArr[sumArr.length - 1]}`;
      let sum = 0;
      for (let i = 0; i < sumArr.length - 4; i++) {
        sum += parseInt("0x" + sumArr[i]);
      }
      const sumHexCheck = sum.toString(16).padStart(8, "0");
      if (sumHexCheck !== fileHexCheck)
        return Modal.error({
          content: "文件校验未通过,请加密(四字节求和校验)!",
        });
      resolve(true);
    };
  });
};

llfididi
281 声望5 粉丝

啊。又是新的一天