将加密对象保存为文件 - cryptojs

时间:2016-12-19 19:47:56

标签: javascript c# encryption cryptojs

我使用cryptojs来加密和解密文件。我还有一个Web服务将加密文件上传到服务器。我可以将ecnrypted对象上传并保存为服务器上的文件,但是当我解密时,文件无法正确打开。我担心的是我是否正确保存了ecnrypted对象。

我最初遵循的教程:http://tutorialzine.com/2013/11/javascript-file-encrypter/

加密方法:

function encrypt() {
      var folderPath = "C:\\User\\test\\javascript-file-encrypter\\";
      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 ct2 = encrypted.toString();
      $.ajax({
        async: 'true',
        url: "http://localhost:51936/WebService1.asmx/FileUpload",
        method: "POST",
        processData: 'false',
        headers: {
            'content-type': "application/x-www-form-urlencoded",
            'cache-control': "no-cache"
        },
        data: { 'folderPath': folderPath, 'uploadData': ct2, 'fileName': sfile.name + '.encrypted' },

        success: function (response) {
            console.log(response);
            debugger;
        },
        error: function (xhr, textStatus, error) {
            debugger;
            console.log(xhr.statusText);
        }
    });
    }
    read.readAsDataURL(sfile);
    }

解密方法:

function decrypt() {

var sfiles = document.getElementById("MainContent_file1");
var sfile = sfiles.files[0];
var freader = new FileReader();
freader.onload = function (e) {

    var decrypted = CryptoJS.AES.decrypt(freader.result, '123456');
    var dct = decrypted.toString(CryptoJS.enc.Latin1);
    //var dct2 = decrypted.toString();
    //console.log(dct);
    //console.log(dct2);
    debugger;
    $.ajax({
        async: 'true',
        url: "http://localhost:51936/WebService1.asmx/FileUpload",
        method: "POST",
        processData: 'false',
        headers: {
            'content-type': "application/x-www-form-urlencoded",
            'cache-control': "no-cache"
        },
        data: { 'folderPath': folderPath, 'uploadData': dct, 'fileName': sfile.name.replace('.encrypted', '') },

        success: function (response) {
            console.log(response);
            debugger;
        },
        error: function (xhr, textStatus, error) {
            debugger;
            console.log(xhr.statusText);
        }
    });

};

freader.readAsText(sfile);

}

webservice方法:

[WebMethod]
    public bool FileUpload(string folderPath, string uploadData, string fileName)
    {

        bool returnValue = false;
        try
        {
            File.WriteAllText(folderPath + fileName, uploadData);
            returnValue = true;

        }
        catch (Exception ex)
        {
            returnValue = false;
        }

        return returnValue;
    }

0 个答案:

没有答案