将C#加密机制代码转换为javascript

时间:2016-10-17 09:52:12

标签: javascript c# encryption aes

我有代码来加密和解密C#中的文件。现在我需要将加密任务移到前端,我需要编写javascript代码来加密.xlsx文件。下面是加密和解密的C#代码:

    var reader = new FileReader();
    reader.onload = function (e) {

        var encrypted = CryptoJS.AES.encrypt(e.target.result, 'myKey123');

        var data = new FormData();


        var encryptedFile = new File([encrypted], file.name, { type: "text/plain", lastModified: new Date() });

        data.append('file', encryptedFile);

        $.ajax({
            url: 'http://localhost:57691/api/WithKey/UploadFile',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function (data) {
                debugger;
            }
        });
    };

    reader.readAsDataURL(file);

我尝试在javascript中创建加密,如下所示:

    function wordsToBytes (words) {
        for (var bytes = [], b = 0; b < words.length * 32; b += 8)
            bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
        return bytes;
    }
  var temp = CryptoJS.enc.Utf16.parse('myKey123');
  var key = wordsToBytes(temp.words);

我也尝试将密钥转换为utf16,如下所示:

  Alamofire.request(endpoint, method: .post, parameters: paramsEncoded, encoding: JSONEncoding.default, headers: headers)
        .responseJSON(completionHandler: { (response) in
            print(response.request) // This returns just the url eg "http://api.com
            print(response.request?.httpBody) // This returns `Optional(85 bytes)`
        })

但没有运气。你能帮助我帮助我做错的地方。在C#中用javascript加密文件的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

这是与C#代码产生相同密文的JavaScript代码。剩下的问题是你需要以某种方式传输它。

var keyWords = CryptoJS.enc.Utf16LE.parse("myKey123");
var encryptedWords = CryptoJS.AES.encrypt("some string", keyWords, { iv: keyWords }).ciphertext;
console.log("Hex: " + encryptedWords.toString());
console.log("Base64: " + encryptedWords.toString(CryptoJS.enc.Base64));
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/aes.js"></script>
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/components/enc-utf16-min.js"></script>