针对文件流加密需要考虑性能问题,所以选择部分文件字节加密,破坏文件内容,达到用户不能随意下载打开文件
ts文件: import { sm2 } from 'sm-crypto'; import { Buffer } from 'buffer'; // 公钥-示例 const publickey_buffer = '0451d6cad24f7719edd7e4e6fccbb2fa9867aec2e609ffeb69ec17570e41daf3073d5e8be23828b41e70c92445e1bc30a992d51c425a83ec0a1c0988b87dce0967'; // 私钥-示例 const privateKey_buffer = '24417f87b5e72f7d6f624b5a82e3c53193b819926dd914d772e179b78d9b4914'; // 截取文件流部分字节加密 export const encryptBufferSlice = function (file, fileName) { getArrayBuffer(file, (result) => { const buffer = Buffer.from(result, 'base64'); const sliceBuffer_head = buffer.slice(0, 100000); const sliceBuffer_tail = buffer.slice(100000); const encryptStr = '04' + sm2.doEncrypt(sliceBuffer_head, publickey_buffer, 1); const encryptBufferArr = Buffer.from(encryptStr, 'hex'); const concatBuffer = Buffer.concat([encryptBufferArr, sliceBuffer_tail]); const blob = new Blob([concatBuffer]); downBlob(blob, fileName); }); }; // 截取文件流部分字节解密 export const decryptBufferSlice = function (file, fileName) { getArrayBuffer(file, (result) => { const buffer = Buffer.from(result, 'hex'); const sliceBuffer_head = buffer.slice(0, 100097); const sliceBuffer_tail = buffer.slice(100097); let strHex = sliceBuffer_head.toString('hex'); strHex = strHex.slice(2); const decryptStr = sm2.doDecrypt(strHex, privateKey_buffer, 1, { output: 'array' }); const decryptBuffer = Buffer.from(decryptStr, 'base64'); const concatBuffer = Buffer.concat([decryptBuffer, sliceBuffer_tail]); const blob = new Blob([concatBuffer]); downBlob(blob, fileName); }); }; // 获取图片ArrayBuffer export const getArrayBuffer = function (file, callback: (result) => void) { const reader = new FileReader(); reader.readAsArrayBuffer(file); reader.addEventListener('load', () => callback(reader.result)); }; // 下载文件 const downBlob = function (blob, filename) { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.setAttribute('href', url); a.setAttribute('download', filename); const event = document.createEvent('MouseEvent'); event.initMouseEvent('click'); a.dispatchEvent(event); };
vue文件引用: const handleBeforeUpload = function (file) { // 解密 decryptBufferSlice(file, '截取前100097字节解密文件.ai'); // 加密 // encryptBufferSlice(file, '截取前100000字节加密文件.ai'); return false; };
标签:文件,vue,const,buffer,sm2,sliceBuffer,Buffer,国密,file From: https://www.cnblogs.com/Joseph-lrc/p/16625065.html