对文件加密并保存:
import { sm4 } from 'sm-crypto'
fetch("你的文件地址") .then(response => response.blob()) .then(byteStream => {
const reader2 = new FileReader();
reader2.onload = function(event) {
const arrayBuffer = event.target.result;
let keyBytes = new Uint8Array(arrayBuffer);
let password = stringToHex("用户输入的密码");
let code = sm4.encrypt(keyBytes,password, {output: 'array'})
let byteStream1 = new Blob([code], { type: 'application/octet-stream' });
let link = document.createElement('a');
link.href = URL.createObjectURL(byteStream1);
link.download = "你保存的文件名";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
// 以ArrayBuffer形式读取文件
reader2.readAsArrayBuffer(byteStream);
})
function stringToHex(str) {
let hex = '';
for (let i = 0; i < str.length; i++) {
hex += str.charCodeAt(i).toString(16);
}
// 如果转换后的16进制字符串长度不足32,则在前面填充0
while (hex.length < 32) {
hex = '0' + hex;
}
return hex;
}
读取文件并解密:
<input type="file" id="keyInput" accept="*" @change="readKeyFile" />
function readKeyFile() {
const keyInput = document.getElementById('keyInput');
const file = keyInput.files[0];
const reader = new FileReader();
reader.onload = function(event) {
const arrayBuffer = event.target.result;
let plainByte = JSON.parse("["+arrayBuffer+"]");
let password = stringToHex("用户输入的密码");
try{
let pBytes = sm4.decrypt(plainByte,password, {output: 'array'});
let prBytes = arrayToBuffer(pBytes);
privateKeyBytes = new Uint8Array(prBytes);
}catch(e){
alert('文件或密码错误');
return;
}
let decoder = new TextDecoder();
let alltext = decoder.decode(privateKeyBytes);
console.log(alltext)//你的文件内容
};
// 读取文件
reader.readAsText(file);
}
function stringToHex(str) {
let hex = '';
for (let i = 0; i < str.length; i++) {
hex += str.charCodeAt(i).toString(16);
}
// 如果转换后的16进制字符串长度不足32,则在前面填充0
while (hex.length < 32) {
hex = '0' + hex;
}
return hex;
}
function arrayToBuffer(arr) {
let buffer = new ArrayBuffer(arr.length);
let view = new Uint8Array(buffer);
for (let i = 0; i < arr.length; i++) {
view[i] = arr[i];
}
return buffer;
}