Securing URL Query Parameters

Working with Liferay 5.2 and ExtJS 3.4 poses a challenge for parameter passing in the URL.

The issue arises when reports are generated based on parameters passed in the URL, allowing manual changes that lead to the generation of unauthorized reports. The proposed solution involves encrypting these parameters in JavaScript before calling the URL, then decrypting them in Java to generate the reports. To ensure security, a unique key should be used for both encryption and decryption processes.

Sample code:

JavaScript:

var numDec = numDec_decsion.getValue();     

var yearDec = yearCorresp_decsion.getValue();       

    var url = "<c:url value='/printer'/>?method=genreport&numDec="+ numDec + 
                        "&yearDec=" + yearDec ;
                window.open(url);

Java:

public void createReport(HttpServletRequest request,
    HttpServletResponse response) throws Exception {
    // Implementation details here
}

 public void createPDFReport(HttpServletResponse response,
        String reportFile, Map parameters, Connection connection) {
    // Implementation details here
}

Generated URL:

http://com.supcom:8080/SupCom/printer?method=genreport&numDec=265&yearDec=1435

Update :

Integrating the SHA1 function into the workflow:

var numDec = numDec_decsion.getValue();

var yearDec = yearCorresp_decsion.getValue();       

    var url = "<c:url value='/printer'/>?method=genreport&numDec="+ SHA1(numDec) + 
                        "&yearDec=" + yearDec ;
                window.open(url);

Here is how the parameter will look like after encryption:

An issue persists regarding the decryption process in the Java class during the execution of the createReport method.

Function for SHA1 algorithm:

/**
*  Secure Hash Algorithm (SHA1)
*  http://www.webtoolkit.info/
**/
// Code snippet here

Answer №1

When it comes to encryption and security measures like MACs, having a key on the client side is essential. However, due to the nature of JavaScript being visible to users, hiding the key effectively becomes a challenge. This means that users can easily access the code and generate a valid URL based on it.


In situations where confidentiality is not a concern, using encryption may not be necessary. Instead, employing a message authentication code (MAC) can suffice. By hashing the desired number - for example, yearDec - with a shared secret known by both the client and server (along with optional salt), you can ensure data integrity:

hYearDec = HASH(HASH(yearDec | key) | key [| salt])

The generated URL should include both yearDec and hYearDec, which are then sent to the server. Here, the server validates that yearDec remains unchanged by running the same hash function as used before, leveraging the supposed secrecy of the key between client and server. The non-secret salt value must also be transmitted to the server.

Even if values were encrypted, an integrity check like a MAC would still be required.

While any hash function such as SHA1 could suffice, utilizing PBKDF2 for deriving a MAC from the data enhances security significantly due to its resilience against attacks.

CryptoJS offers suitable functions for achieving this: source.

var secretKey = "someSecretRandomString_k345kretiu46kzjnh";
var requestParameters = "yearDec=123456"; // send this
var salt = CryptoJS.lib.WordArray.random(128/8);
var key = CryptoJS.PBKDF2(requestParameters+secretKey, salt, { keySize: 256/32, iterations: 500 });
var saltHex = salt.toString(); // send this
var macHex = key.toString() // send this

On the server end:

String plaintext = "yearDec=123456"; // request parameter
String secretKey = "someSecretRandomString_k345kretiu46kzjnh";
plaintext += secretKey; // add key in the same way as in the client
char[] plaintextChars = new char[plaintext.length()];
plaintext.getChars(0, plaintext.length(), plaintextChars, 0);
int keySize = 256; // during system setup
int iterations = 500; // during system setup
String macHex = "bf92577e37627dbdc4a67510510c130aca6cf8e2e8bed0ea218f6cd909e3270d";  // further request parameters
String saltHex = "639a8d66d6a4fac8a39ce7c8b42fe0d8"; // further request parameters

// convert
byte[] mac = hexStringToByteArray(macHex);
byte[] salt = hexStringToByteArray(saltHex);

// derive
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec ks = new PBEKeySpec(plaintextChars, salt, iterations, keySize);
SecretKey s = f.generateSecret(ks);

// check
Arrays.equals(s.getEncoded(), mac);

I refer to this post for converting hex to byte arrays:

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

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

How can you determine if a specific variable exists within an array using an if statement?

Currently, I have designed a program that incorporates methods such as inputArray, selectionSort, binarySearch, and printArray. However, I am facing some difficulty while working on the main method. I need assistance in creating the main method that calls ...

What is the best way to fill the MongoDB post schema with every comment for the post?

I have created two schemas, one for posts and another for comments. const PostSchema = new Schema( { title: { type: String, required: true }, text: { type: String, required: true }, author: { type: Schema.Types.ObjectId, ref: 'User' ...

Fetch data from Firestore when the page loads using the useEffect hook

Below is the simplified code snippet I am currently using: import { useState, useEffect, useContext } from 'react' import { useRouter } from 'next/router' import { firestore } from './firebase-config' import { getDoc, doc } f ...

Combining Jquery with Objects and Strings

Having a bit of trouble with a small issue that I can't seem to figure out. Let me explain... So, I'm creating an input like this... var input = $('<input/>'); When I append it like this, everything works fine: $(this).append( ...

Modifying the color of multiple cells simultaneously

I'm currently facing an issue where I need to change the cell color of multiple cells at once, all stored within a specific range. However, I only want certain cells to change based on a particular condition. While I can manually change each cell, it& ...

PHP is unable to render Google Maps on the webpage

My PHP code retrieves location information from a database (test) and table named manu, created using phpmyadmin in Wamp. It then displays those locations on a map with markers, showing latitude and longitude values. UPDATED <? $dbname =&ap ...

Disabling dynamic color updates upon refresh

I am currently using chartjs and I want to generate new random colors each time the page is refreshed. However, I need these colors to remain fixed and not change after a page refresh or reload. Below is the function I am working with: getRandomRgb() { ...

The password prompt window refuses to align with the center of the screen. This

I've been struggling to position the Javascript popup notification using the width, height, top, and left parameters in the window.open function. No matter what I attempt, it stubbornly remains in the top-left corner. Can someone offer some guidance o ...

Modify section background color for every iteration in an image carousel

Is it possible to dynamically change the background color of the cd-hero section each time a new image is loaded in a simple slider on the home page? Can this be achieved by storing predefined colors in an array so that different images trigger different b ...

When a user clicks on an anchor tag, close the current window, open a new window, and pass the

I have a scenario where I have an anchor tag that triggers the opening of a window on click. In this newly opened window, there is a table with a column containing another anchor tag. Here is what I am trying to achieve: Code for the anchor tag: functio ...

DatagramSocket - connecting to local socket on localhost

In the documentation provided by official source, it mentions a specific constructor: DatagramSocket (int port) Clarification is needed: if a port is associated with a DatagramSocket, does all UDP traffic automatically pass through that port, regardless ...

Why isn't my Selenium Java test script displaying a basic confirmation message as intended?

I've been working on completing a test script in Java and everything is functioning perfectly. The goal is to display a confirmation message indicating that the account creation was successful after all the preceding steps have run. In order to achie ...

Tips for sending a parameter to a URL from a controller using AngularJS

I am currently working on a feature where I need to combine adding and editing functionalities on one page. The items are listed in a table below, and when the edit button is clicked, I want to pass the ID of that specific item in the URL. This way, if the ...

Do you know the term for when JavaScript is utilized to display specific sections of a png image?

Imagine you have an image file in the format of a PNG which includes various icons intended for use on a website. How can JavaScript be utilized to choose and showcase a specific icon from that image? It's a technique I've observed in practice, b ...

Stopping video playback when hovering over it

Can anyone help me modify this code so that a video plays only when hovering over it, and stops playing once the hover ends? What changes should I make to the JavaScript portion of the code for this functionality? <div class="padding-box height-40"&g ...

Determining the authenticity of a detected face: Tips and tricks

Currently, I am working on a security project where I need to implement face detection. The objective is to take a specific action if a face is detected, and close the application if no face is detected. Everything is functioning perfectly. I am utilizing ...

How can I quickly upload a file while load balancing?

I recently developed an application in node js that includes a load balancing feature. I set up separate servers - one for the database and another for managing requests. The issue arises when users upload files using multer in Express, as the file gets up ...

Restore Bootstrap Dropdown values to their initial settings when clicked

I need a button that can reset all filter dropdown values to their default values. The current code I have only changes all values to "Filter" when reset, but I specifically need it to reset to "Car brand" and "Model". Here's my code: // set.... $(" ...

Are routes in Next.js easy for search engines to crawl?

Currently, I am developing a movie application using NextJS to enhance my skills. The homepage features each movie's title and a brief description. When a user clicks on a movie, they are taken to a dedicated page that showcases more details about the ...

Update and republish an outdated npm package

After successfully publishing an npm package, I attempted to make an update which unfortunately resulted in some issues. It seems that I made a mistake during the build process. Since it had been a year since my last update, I have forgotten the exact step ...