Encrypting Passwords in Browser Cookies and Decrypting with PHP

In today's digital age, web security is paramount. One of the critical aspects of securing your website is ensuring that sensitive information, such as passwords, is protected. Storing passwords in plain text can lead to severe security breaches. This blog post will guide you through encrypting passwords and safely storing them in cookies using JavaScript.

In our previous blog post, we delved into enhancing the security of local storage in ElectronJS applications using CryptoJS to encrypt passwords. Building on that foundation, this post will guide you through an equally crucial aspect of web security: encrypting passwords in browser cookies using JavaScript and decrypting them on the server side with PHP using OpenSSL. By leveraging these techniques, you can bolster the security of your user data, ensuring that sensitive information remains protected both on the client side and during its transit to the backend. Join us as we explore step-by-step how to implement this robust encryption and decryption process, making your web applications more secure than ever.

Step 1: Setting Up the HTML Form

First, create a simple multi-step signup form. This form will guide the user through entering their information, including a password.

<form id="signupForm" onsubmit="return false;">
    <div class="tab active">
        <h3>Step 1:</h3>
        <!-- User input fields for Step 1 -->
        <input type="text" name="name" placeholder="Name" required>
        <input type="text" name="email" placeholder="Email" required>
    </div>
    <div class="tab">
        <h3>Step 2:</h3>
        <!-- User input fields for Step 2 -->
        <input type="password" id="password" name="password" placeholder="Password" required>
    </div>
    <div class="tab">
        <h3>Step 3:</h3>
        <p>Confirmation</p>
    </div>
    <div style="overflow:auto;">
        <div style="float:right;">
            <button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
            <button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
            <button type="button" id="submitBtn" onclick="handleSubmit()" style="display:none;">Encrypt & Submit</button>
        </div>
    </div>
    <div style="text-align:center;margin-top:40px;">
        <span class="step active"></span>
        <span class="step"></span>
        <span class="step"></span>
    </div>
</form>
        

Step 2: Adding JavaScript for Password Encryption

Next, we’ll implement the JavaScript needed to encrypt the password using the Web Crypto API before storing it in a cookie.

   <script>
        const key = 'YOUR-SECRET-KEY'; // Updated secret key
        const iv = new Uint8Array([21, 31, 41, 51, 61, 71, 81, 91, 101, 111, 121, 131, 141, 151, 161, 171]); // Shared IV

        async function Jsencrypt(plaintext, key, iv) {
            const encoder = new TextEncoder();
            const keyBuffer = encoder.encode(key);
            const hash = await crypto.subtle.digest('SHA-256', keyBuffer);
            const cryptoKey = await crypto.subtle.importKey('raw', hash, { name: 'AES-CBC' }, false, ['encrypt']);
            const plaintextBuffer = encoder.encode(plaintext);
            const encryptedBuffer = await crypto.subtle.encrypt({ name: 'AES-CBC', iv: iv }, cryptoKey, plaintextBuffer);
            return btoa(String.fromCharCode(...new Uint8Array(encryptedBuffer)));
        }

        function handleSubmit() {
            var password = document.getElementById('password').value;
            Jsencrypt(password, key, iv).then(encryptedPassword => {

document.cookie = 'secure_password=' + encryptedPassword + '; path=/; secure; httponly; samesite=Strict';
                document.getElementById("originalPassword").innerText = password;
                document.getElementById("encryptedPassword").innerText = encryptedPassword;
                document.getElementById("result").style.display = "block";
            });
        }

        function showTab(n) {
            var x = document.getElementsByClassName("tab");
            for (var i = 0; i < x.length; i++) {
                x[i].classList.remove("active");
            }
            x[n].classList.add("active");
            if (n == 0) {
                document.getElementById("prevBtn").style.display = "none";
            } else {
                document.getElementById("prevBtn").style.display = "inline";
            }
            if (n == (x.length - 1)) {
                document.getElementById("nextBtn").style.display = "none";
                document.getElementById("submitBtn").style.display = "inline";
            } else {
                document.getElementById("nextBtn").style.display = "inline";
                document.getElementById("submitBtn").style.display = "none";
            }
            fixStepIndicator(n);
        }

        function nextPrev(n) {
            var x = document.getElementsByClassName("tab");
            if (n == 1 && !validateForm()) return false;
            x[currentTab].classList.remove("active");
            currentTab = currentTab + n;
            showTab(currentTab);
        }

        function validateForm() {
            var x, y, i, valid = true;
            x = document.getElementsByClassName("tab");
            y = x[currentTab].getElementsByTagName("input");
            for (i = 0; i < y.length; i++) {
                if (y[i].value == "") {
                    y[i].classList.add("invalid");
                    valid = false;
                }
            }
            if (valid) {
                document.getElementsByClassName("step")[currentTab].classList.add("finish");
            }
            return valid;
        }

        function fixStepIndicator(n) {
            var i, x = document.getElementsByClassName("step");
            for (i = 0; i < x.length; i++) {
                x[i].classList.remove("active");
            }
            x[n].classList.add("active");
        }

        var currentTab = 0;
        showTab(currentTab);
    </script>
        

Step 3: Adding CSS for the Form Style

To make the form visually appealing, let's add some CSS styles.

<style>
.tab {
    display: none;
}
.tab.active {
    display: block;
}
.step {
    display: inline-block;
    padding: 10px;
    border: 1px solid #000;
    margin-right: 5px;
}
.step.active {
    background-color: #4CAF50;
    color: white;
}
.step.finish {
    background-color: #4CAF50;
}
.result {
    margin-top: 20px;
    padding: 10px;
    border: 1px solid #000;
    display: none;
}
</style>
        

Step 4: Live Demo


Step 2:

Step 3:

Confirm form submit


Form Results

Original Password:

Encrypted Password:



Step 5: Process to Decrypt the Password in Backend - PHP

Below is the PHP code to decrypt data that was encrypted using the AES-CBC method with a shared key and IV:


<?php
function decrypt($encryptedText, $key, $iv) {
    // Decode the base64 encoded encrypted text
    $encryptedData = base64_decode($encryptedText);

    // Create a hash of the key using SHA-256
    $hash = hash('sha256', $key, true);

    // Decrypt the data using the AES-256-CBC algorithm
    $decryptedData = openssl_decrypt($encryptedData, 'aes-256-cbc', $hash, OPENSSL_RAW_DATA, $iv);

    return $decryptedData;
}

// Example usage
$encryptedText = 'YOUR_ENCRYPTED_TEXT_HERE';
$key = 'YOUR-SECRET-KEY'; // Updated secret key
$iv = chr(21) . chr(31) . chr(41) . chr(51) . chr(61) . chr(71) . chr(81) . chr(91) . chr(101) . chr(111) . chr(121) . chr(131) . chr(141) . chr(151) . chr(161) . chr(171); // Shared IV

$decryptedText = decrypt($encryptedText, $key, $iv);
echo "Decrypted Text: " . $decryptedText;
?>

    

Save this code as a PHP file (e.g., decrypt.php) and run it on your server to see the decrypted text.

Conclusion

In today’s digital era, ensuring the security of sensitive information like passwords is crucial. By following the steps outlined in this blog post, you can enhance your website’s security by encrypting passwords before storing them in cookies. This approach not only protects sensitive data but also builds trust with your users by demonstrating a commitment to their privacy and security.

Implementing a secure multi-step form, along with robust encryption using the Web Crypto API, helps mitigate potential security threats such as cross-site scripting (XSS) attacks. It’s important to stay vigilant and continuously update your security practices to adapt to emerging threats.

Remember, securing your web applications is an ongoing process. Regular audits, updates, and adopting best practices are key to maintaining a secure environment for your users. By taking these proactive steps, you’re not just protecting your site but also contributing to a safer web for everyone.

Stay secure, stay vigilant, and 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.