通过cryptojs加密文件会使文件大小增加近30%。这在使用C#中的AESManaged类解密文件时导致问题。如何将加密对象保存为文件而不增加太多的大小?
JS中的文件加密:
function esp() {
selectedFiles = document.getElementById("MainContent_file1");
var sfile = selectedFiles.files[0];
var read = new FileReader();
read.onload = function (e) {
var encrypted = CryptoJS.AES.encrypt(read.result, '123456');
var ct = encrypted.toString();
debugger;
$.ajax({
async: 'true',
url: "http://localhost:51936/WebService1.asmx/FileUpload",
method: "POST",
processData: 'false',
headers: {
'content-type': "application/json",
'cache-control': "no-cache"
},
data: JSON.stringify({ 'folderPath': folderPath, 'uploadData': ct, 'fileName': sfile.name + '.encrypted' }),
success: function (response) {
console.log(response);
},
error: function (xhr, textStatus, error) {
console.log(xhr.statusText);
}
});
}
read.readAsDataURL(sfile);
}
将加密对象保存为文件的Web服务:
[WebMethod]
public bool FileUpload(string folderPath, string uploadData, string fileName)
{
//NOTE: A CODE SCAN TOOL is showing a PATH TRAVERSAL ERROR. a folderPath can be retrieve from DATABASE for remove the error but would affect the performance which is not advisable.
bool returnValue = false;
try
{
byte[] byteUploadFile = Convert.FromBase64String(uploadData);
BinaryWriter binWriter = new BinaryWriter(File.Open(Path.Combine(folderPath, fileName), FileMode.Create, FileAccess.ReadWrite));
binWriter.Write(byteUploadFile);
binWriter.Close();
returnValue = true;
}
catch (Exception ex)
{
returnValue = false;
}
return returnValue;
}
答案 0 :(得分:0)
我将加密字符串(base64)保存为文件的方式是正确的。但是,为了正确解密并从解密的字符串中生成原始文件,需要进行一些剥离。请参阅下文,了解我如何从加密文件中获取解密字符串并将其另存为原始文件。
Mywebservice.Mywebservice dts = new Mywebservice.Mywebservice();
using (var rijAlg = new RijndaelManaged())
{
rijAlg.Key = keybytes;
rijAlg.IV = iv;
var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
using (var msDecrypt = new MemoryStream(cipherText))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
plaintext = plaintext.Substring(23); //This is the part to strip. The first
//23 chars are the mime type of the file. Remove that and just save the string data.
string name = filename.Replace(".encrypted", "");
dts.FileUpload(folderPath, plaintext, name); //call the same webservice used for saving encrypted object.
}