Encrypt and decrypt files using AES encryption technology with the help of the crypto-js library

I am currently facing a requirement where I am unable to decrypt an encrypted file. Every time I try, the generated file ends up being damaged and cannot be opened. I'm unsure of where the issue lies within my code implementation in VUE.

Encode() {
           let CryptoJS = require("crypto-js");
            this.file_mime = this.file.type;
            this.file_name = this.file.name;
            let reader = new FileReader();
            reader.onload = () => {
                let key = "1234567887654321";
                // let wordArray = CryptoJS.lib.WordArray.create(reader.result);
                // let plaintext = CryptoJS.enc.Hex.stringify(wordArray);
                let encrypted = CryptoJS.AES.encrypt(reader.result, key).toString();

                this.file2 = new Blob([encrypted], {
                    type: this.file_mime
                });
                const a = document.createElement("a");
                const url = window.URL.createObjectURL(this.file2);
                const filename = this.file_name;
                a.href = url;
                a.download = filename;
                a.click();
                window.URL.revokeObjectURL(url);
            };
            reader.readAsBinaryString(this.file);
        }

Decode() {
            let CryptoJS = require("crypto-js");
            let reader = new FileReader();
            reader.onload = () => {
                let key = "1234567887654321";
                let decrypted = CryptoJS.AES.decrypt(reader.result, key).toString(CryptoJS.enc.Utf8)
                this.file2 = new Blob([decrypted], {type: this.file_mime});
                const a = document.createElement("a");
                const url = window.URL.createObjectURL(this.file2);
                const filename = this.file_name;
                a.href = url;
                a.download = filename;
                a.click();
                window.URL.revokeObjectURL(url);
            };
            reader.readAsBinaryString(this.file);
        }

Answer №1

When working with JavaScript, it's important to understand the different types of arrays available. These include Array, ArrayBuffer, and typed arrays. Additionally, CryptoJS uses WordArray, requiring proper conversion between these types.

For encryption tasks, it is recommended to replace the usage of FileReader.readAsBinaryString with FileReader.readAsArrayBuffer. This method returns binary data from a file as an ArrayBuffer, which can then be converted to a WordArray for direct processing by CryptoJS.AES.encrypt. The resulting ciphertext is returned as a CipherParams object in Base64 encoded string format following the OpenSSL standard.

During encryption, the key provided to CryptoJS.AES.encrypt is interpreted as a passphrase, generating a random 8-byte salt using the same algorithm employed by OpenSSL to derive the key and initialization vector. The encrypted data starts with specific markers like U2FsdGVkX1 within its Base64 encoding according to the OpenSSL format standards.

Modifications made to the encryption process are outlined below:

function encrypt(input) {
    var file = input.files[0];
    var reader = new FileReader();
    reader.onload = () => {
        var key = "1234567887654321";
        var wordArray = CryptoJS.lib.WordArray.create(reader.result);          
        var encrypted = CryptoJS.AES.encrypt(wordArray, key).toString();        

        var fileEnc = new Blob([encrypted]);                                   
        var a = document.createElement("a");
        var url = window.URL.createObjectURL(fileEnc);
        var filename = file.name + ".enc";
        a.href = url;
        a.download = filename;
        a.click();
        window.URL.revokeObjectURL(url);
    };
    reader.readAsArrayBuffer(file);
}

It is essential to note that encrypted data result in larger file sizes due to the nature of Base64 encoding overhead during encryption compared to unencrypted data.

Similarly, for decryption operations, replacing FileReader.readAsBinaryString with FileReader.readAsText enables passing the Base64 encoded data directly to CryptoJS.AES.decrypt. The decrypted content is returned as a WordArray, necessitating further conversion steps to create the final output blob.

function decrypt(input) {
    var file = input.files[0];
    var reader = new FileReader();
    reader.onload = () => {
        var key = "1234567887654321";  

        var decrypted = CryptoJS.AES.decrypt(reader.result, key);               
        var typedArray = convertWordArrayToUint8Array(decrypted);               

        var fileDec = new Blob([typedArray]);                                   

        var a = document.createElement("a");
        var url = window.URL.createObjectURL(fileDec);
        var filename = file.name.substr(0, file.name.length - 4) + ".dec";
        a.href = url;
        a.download = filename;
        a.click();
        window.URL.revokeObjectURL(url);
    };
    reader.readAsText(file);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Scrolling horizontally using jQuery and CSS

I have been experimenting with creating a horizontal scrolling page that moves to the right when scrolling down and to the left when scrolling up. Here is the current code: HTML <div class="scroll-sections"> <section id=&quo ...

Make sure to close any existing Featherlight windows before trying to open another one

I'm setting up multiple featherlight instances when the page loads jQuery('.feedback').featherlight(jQuery( "#feedback-box" ), { closeIcon: 'close'}); jQuery('#imprint').featherlight(jQuery( "#imprint-box" ), { closeIcon ...

Ways to access the specified variable in JavaScript

How can I get to the header of a variable? For example, in the Redux Framework WordPress plugin, there is a variable [redux.args.opt_name]. How do I find the define line for this variable? Another Question: What does the use of two single quotes in the &a ...

Is it Possible to Achieve Callbacks From AJAX to PHP Despite the Inability to Serialize Closures?

Question How can I incorporate a PHP callback passed via AJAX, where the callback is executed by the page requested through AJAX? The Scenario Comments are submitted through AJAX with parameters serialized and encrypted for security. The issue arises wh ...

Building a custom WebRTC Unity to JavaScript client for one-way video streaming within the local network

In this project, Unity is used to capture video and it communicates with JavaScript via WebRTC. Despite successful communication between the two clients, the JavaScript client is unable to display any video from the Unity client. The issue of no video out ...

Hiding the original shape with ClipPath in d3 ReactJS

Currently diving into the world of D3 and ReactJS, I attempted to clip a circle with a straight line, but struggled to grasp how it functions. Below is the HTML code snippet used to draw an image: <div> <svg xmlns="http://www.w3.org/2000/svg" ...

Optimizing the use of .less files in an expansive angularjs application

Currently, I am in the process of developing a large-scale application using AngularJS as a Single Page App. All the html files have been organized under the Views folder as shown here. Views Sample sample.html sampleheader.html ...

Ways to automatically refresh the page after modifying the content inside a div

I have been attempting to modify the text within a div without much success. After searching around, I have found the following code: <script type="text/javascript"> function UpdateDiv(fieldname, text) { document.getElementById(fieldname ...

Using jQuery to locate the dimensions of an image and then adjusting the height and width of a div using

I'm currently working on a project where I need jQuery to determine the size of each image (approximately 8-10 images per page) within an Owl Carousel. However, every time I check in the developer tools, all I see is width: 0px, height: 0px Here&apos ...

Material-UI now offers the ability to customize the shadows array within createMuiTheme to support up to 25 different elevations

Currently working on removing shadows in the Material-UI theme. Came across this useful solution that fixed the issue. However, encountered an error related to this topic. const theme = createMuiTheme({ palette: { primary: { light: red[300], ...

Substitute the ajax reply with the text currently displayed

I am facing an issue with the AJAX response in my HTML page. Currently, the response is being appended on top of the existing text instead of replacing it. Here is a snippet of my code: <html> <head> <h2>This is a test</h2> ...

Different methods for looping through undefined values within Arrays

While exploring the use of .map, I made an interesting discovery regarding arrays with holes, where certain indices are defined while others remain undefined: // Holed var array = []; array[0] = 1; array[2] = 3; array // => [1, undefined, 3]; // Not H ...

Using Javascript and the Document Object Model (DOM) to parse a Key/Value

When a server sends a string to the Firefox Browser, it is in the following format: "KEY:a1 VAL:123.45" This string can consist of multiple records like this. Below is the code I wrote to handle this information: var e; var reply = request.resp ...

ways to incorporate audio into a hyperlink

Hello everyone, I am looking to incorporate a sound into my link. Can anyone suggest a jquery or javascript method to achieve this? I tried the following code but it didn't work: <div align="center"><a href="our_product.html" class="footerm ...

Vue vee-validate ensures that input forms are validated when used in conjunction with a router-link

Currently, I am utilizing vee-validate for validating a form that contains multiple inputs. Due to the number of inputs, I have split this form into 3 pages and incorporated <router-link/> buttons for seamless navigation between them. I am curious ...

Changing Marker Colors in OpenLayers After Importing GPX Data: A Quick Guide

Check out this link for a code tutorial on importing GPX files and displaying map markers. I successfully implemented this code to show map markers. Is there a way to customize the color of the markers? Edit: var fill = new Fill({ color: 'rgba(2 ...

Having trouble calculating the total sum within a for loop

I have a special function inside a loop that generates an array of objects. My goal is to calculate the total value returned by this function, but unfortunately I am not getting the correct sum. The function itself is working properly, however, I am unable ...

The state is well-defined within the "ComponentDidMount" function, however, it appears to be undefined in the

After extracting data from my "ComponentDidMount" function and loading it into my state, I verified the presence of the data by console logging the value successfully. However, when trying to access the state in the same manner within the return statement ...

Issue with HTML5 Video Play on Hover Functionality Ceases to Work Upon Loading Dynamic Content

I recently implemented a feature on my WordPress site that allows videos to start playing when the mouse hovers over their thumbnails and pause when it leaves. However, I encountered an issue where this function works perfectly upon initial page load but f ...

handlebars.js template to check the condition based on the last item in an array

I am currently utilizing handlebars.js as my templating engine and am interested in creating a conditional segment that will only display if it happens to be the final item within an array located in the templates configuration object. { columns: [{< ...