Saving an encrypted file locally that is created using JavaScript

I am using crypto-js and the following code to encrypt files. It seems they are encrypting them, and I see stringin alert().

Now I need to be able to save the encrypted file somewhere on my computer. I run this file locally on my computer.

I can not find a working solution for this scenario!

This is my complete code:

<!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="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>


      <!--
  https://cdnjs.com/libraries/crypto-js
  -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>


  <!--[if lt IE 9]>
    <script src="https://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->

    <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');
                    ecr = encrypted.toString();
                    alert(encrypted);



                }

                reader.readAsDataURL(file)
                $('#thelist').append('FILES: ' + file.name + '<br>')
            })
        })
    });

    </script>
</head>
<body>
    <input type="file" id="file-input">
    <div id="thelist"></div>


    <input type="button" id="button" value="Save" />
</body>
</html>

Can anyone consult on this?

+4
source share
1 answer

If you don't care about IE9 (or older), you can create Blobencrypted text to store:

var blob = new Blob([encrypted], { type: 'text/plain' });

, , Blob . MDN (. Blob ctor MDN)

var typedArray = GetTheTypedArraySomehow();
var blob = new Blob([typedArray], {type: 'application/octet-binary'});

<a> blob:

var link = document.createElement('a');
link.download = 'Encrypted document';
link.href = URL.createObjectURL(blob);

, :

document.body.appendChild(link);
link.click();
document.body.removeChild(link);

IE8, , Wikipedia , SO: , .

+3

Source: https://habr.com/ru/post/1684116/


All Articles