【发布时间】:2017-01-24 20:58:41
【问题描述】:
通过 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;
}
【问题讨论】:
-
您确定文件大小增加的原因了吗?我敢打赌,结果是以 base64 给出的,这就是您要写入文件的内容。
-
我正在从 base64 获取字节并写入文件。见webservice方法。
-
但是你写的是base64吗?你是在写原始字节还是用 base64 编码的字节?
-
8 位无符号。
Convert.FromBase64String。我不确定这个方法的输出是否是原始的。 -
如果您发布到 HTTPS 网址,这不会成为问题,因为数据将在传输过程中被加密。使用您的方法,您将如何保护 AES 密钥?
标签: c# encryption cryptography aes cryptojs