Enhancing Local Storage Security in Electron.js Apps with crypto-js

Introduction

Electron.js is a powerful framework for building cross-platform desktop applications with web technologies. When storing sensitive data such as user credentials in local storage, it's crucial to ensure that the data is securely encrypted to protect against potential security threats. In this guide, we'll walk you through encrypting and decrypting data in local storage using crypto-js.

Prerequisites

To follow this guide, you will need:

  • Node.js installed on your computer.
  • Basic knowledge of JavaScript and Electron.js.

Step 1: Setting Up Your Electron.js Project

First, create a new directory for your Electron.js project and initialize it:

mkdir electron-encryption-app
cd electron-encryption-app
npm init -y
npm install electron crypto-js

Step 2: Creating the Main Process

Create a main.js file. This file will create the browser window and load your application.

const { app, BrowserWindow } = require('electron');
const path = require('path');
function createWindow() {
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            contextIsolation: true,
            enableRemoteModule: false
        }
    });

    mainWindow.loadFile('index.html'); // Replace with your actual HTML file if different
}

app.on('ready', createWindow);

Step 3: Creating the Preload Script

Create a preload.js file. This script will expose secure APIs to the renderer process and handle encryption and decryption of data using crypto-js.

const { contextBridge } = require('electron');
const CryptoJS = require('crypto-js');

const secretKey = 'your-secret-key'; // Replace with your actual secret key

console.log('Preload script running...'); // Log to confirm script execution

contextBridge.exposeInMainWorld('electron', {
    saveData: (key, data) => {
        console.log('Saving data...'); // Log for debugging
        const encryptedData = CryptoJS.AES.encrypt(data, secretKey).toString();
        localStorage.setItem(key, encryptedData);
        console.log('Data saved:', encryptedData); // Log for debugging
    },
    getData: (key) => {
        console.log('Getting data...'); // Log for debugging
        const encryptedData = localStorage.getItem(key);
        if (encryptedData) {
const decryptedData = CryptoJS.AES.decrypt(encryptedData, secretKey).toString(CryptoJS.enc.Utf8);
            console.log('Data retrieved:', decryptedData); // Log for debugging
            return decryptedData;
        }
        return null;
    }
});

Step 4: Creating the Renderer Script

Create an index.html file with the following content. This file will handle saving and retrieving the encrypted data.

<!DOCTYPE html>
<html>
<head>
    <title>Electron Encryption Example</title>
</head>
<body>
    <h1>Electron Encryption Example</h1>
    <form id="dataForm">
        <label for="dataInput">Enter Data:</label>
        <input type="text" id="dataInput" required>
        <button type="submit">Save Data</button>
    </form>
    <h2>Stored Data:</h2>
    <p id="storedData"></p>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Retrieve and display stored data
        const storedData = window.electron.getData('myDataKey');
        if (storedData) {
            document.getElementById('storedData').textContent = storedData;
        }

        // Handle form submission
        document.getElementById('dataForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const data = document.getElementById('dataInput').value;
            window.electron.saveData('myDataKey', data);

            // Display the stored data
            document.getElementById('storedData').textContent = data;
            document.getElementById('dataInput').value = ''; // Clear the input field
        });
    });
    </script>
</body>
</html>

Step 5: Running Your Electron.js App

Update your package.json to include a start script for Electron:

"scripts": {
    "start": "electron ."
}

Now, you can run your Electron.js app:

npm start

Conclusion

By following these steps, you've created an Electron.js application that securely stores data in local storage using encryption. This setup enhances security by ensuring that sensitive information is protected. Feel free to customize the app further to meet your specific needs.

Remember, always keep your secret key secure and regularly update your dependencies to maintain the security of your application. Happy coding!

0 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *


You may like to read


Follow Us

Sponsored Ads

GranNino Ads

Newsletter

Subscribe to our Newsletter to read our latest posts at first

We would not spam your inbox! Promise
Get In Touch

© Fullstack Coding Tips. All Rights Reserved.