使用CryptoJS进行文件加密 - 客户端

时间:2016-11-07 20:38:41

标签: javascript jquery encryption filereader cryptojs

我正在尝试加密位于客户端的文件夹中的所有文件。我有以下代码,但收到错误。我不完全确定错误。

错误: 未捕获的TypeError:无法读取属性'长度'在html中第16行的未定义(...)

的index.html

<!DOCTYPE html>
<html>
<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>Get Directory</title>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="assets/js/aes.js"></script>
    <script type="text/javascript"> 
    $(document).ready(function(){
        $("#file-input").on("change", function(e){
            var thefiles = e.target.files;
            var reader = new FileReader();
            $.each(thefiles, function(i, item){
                var thefile = item;
                reader.onload = function(){
                    var encrypted = CryptoJS.AES.encrypt(thefile, '12334');
                };
                reader.readAsDataURL(thefile);
                $("#thelist").append("FILES: " + thefile.name + "<br />");;
            });
        });
    });
    </script>
</head>
<body>
    <input type="file" id="file-input" webkitdirectory="" directory="">
    <div id="thelist"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

阅读所有评论

<!DOCTYPE html>
<html>
<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>Get Directory</title>
    <!-- Update your jQuery version??? -->
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="assets/js/aes.js"></script>
    <script> // type="text/javascript" is unnecessary in html5

    // Short version of doing `$(document).ready(function(){`
    // and safer naming conflicts with $
    jQuery(function($) { 

        $('#file-input').on('change', function() {

            // You can't use the same reader for all the files
            // var reader = new FileReader

            $.each(this.files, function(i, file) {

                // Uses different reader for all files
                var reader = new FileReader

                reader.onload = function() {
                    // reader.result refer to dataUrl
                    // theFile is the blob... CryptoJS wants a string...
                    var encrypted = CryptoJS.AES.encrypt(reader.result, '12334')
                }

                reader.readAsDataURL(file)
                $('#thelist').append('FILES: ' + file.name + '<br>')
            })
        })
    })
    </script>
</head>
<body>
    <input type="file" id="file-input" webkitdirectory="" directory="">
    <div id="thelist"></div>
</body>
</html>
顺便说一句,浏览器内置了一个现代标准的Crypto lib ...也许尝试使用它?如果需要,可以使用polyfill?